A guide to asynchronously printing the elements in queue q

Can someone help me understand how to properly print the items in the q after all results are pushed in this program?

function asyncAdd(a,b,callback) {
    setTimeout(function() {
        return callback(a+b);
    },0);
}

var q = [];
var ctr = 0;
for (var i=0; i<9; i++) {
    (function(i) {
       var res = asyncAdd(i, 0, printRes);
       q.push(res);
    })(i);
}


function done(q) {
    console.log("done"+q);
}

function printRes(res) {
    return res;
}

Answer №1

Take a look at my updated code snippet:

function asyncMultiply(x, y, callback) {
    callback(x * y);
}

var products = [];
var count = 0;
var limit = 10;
for (var j = 1; j <= limit; j++) {
    asyncMultiply(j, 2, displayResult);       
}

function finish(products) {
    console.log("All computations completed: " + products);
}

function displayResult(result) {
    products.push(result);
    if (products.length === limit)
        finish(products);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is a Promise nested within another Promise?

My current task involves retrieving the lat/long of 2 addresses using promises. Once this initial promise is resolved, I need to parse a file that correlates with these lat/long coordinates. Everything works as expected and I can handle the values in the ...

The field 'name' remains unchanged

I am in the process of developing a VS CODE THEME MAKER that generates a customized JSON file based on user input for colors. Below is all the necessary code: import download from 'downloadjs'; import React, { useState } from 'react'; i ...

Tips for converting response text into HTML code

I am receiving a text response like this <span class='text-4xl'>description1</span> When I display it on the screen: import React,{useContext, useEffect} from 'react'; import blogsContext from '../context/blogsCon ...

The malfunction of Angular's tree component

After installing and importing the Angular tree component, I followed the basic example provided in order to set it up. However, upon following the steps outlined on , I encountered an issue where only the root node is visible without expanding. Could some ...

Minimize an array by organizing objects based on the proximity of their numbers

My array contains the following data: [ { "begin": 870, "end": 889, "spanType": ["plan", "gt-plan"] }, { "begin": 890, "end": 925, "spanType": ["plan", "gt-plan"] }, { "begin": 926, "end": 938, "spanType": ["plan", "gt-plan"] }, { "begin": 939, ...

Safely displaying a JavaScript escaped string in PHP output

When taking user inputs safely using encodeURIComponent() (and encodeURI() for e-mails) and sending them to PHP via AJAX, I escape the output and store it in a $_SESSION[] which is later echoed. I am looking for a way to print this to HTML normally without ...

Is it beneficial to create a separate component for React form elements?

I've come across advice that suggests when unsure, turning an element into a component is a good idea. But what are the actual benefits of converting form elements like <input /> into components? Let's consider the following example: cons ...

Retrieve information from a sensor within an Express server and display it on the user interface

Looking for suggestions on resolving a challenge: I have a Node.js module that retrieves data from a sensor, and I am interested in incorporating a UI element to showcase the sensor data (either in real-time or pseudo-realtime). Is there a way to establ ...

Can data be sent back from a webpage to the main server?

I apologize in advance if this question seems silly, but I've been working on setting up a server that can handle both HTTP and websockets. My goal is to have the action of pressing a button trigger a change in a value within the server, which can the ...

Decoding the JSON response object

Upon receiving a JSON response from an Ajax call, I handle it in the following way: oData = JSON.parse(sReply); Within this code snippet, we have the object definition as follows: var oData = new cData(); function cData() { this.Email = ""; thi ...

Steps for loading a directive into a module after instantiation with requirejs

Let me share a bit about my current challenge. Initially, I had all the necessary directive files injected into my main module in app.js using requirejs paths, and everything was functioning smoothly. It looked something like this: define(['angularAM ...

Authentication Failure: Passport azure-ad Verify Callback Is Not Triggered

When utilizing passport (with the passport-azure-ad strategy) for request authentication, I have encountered an issue. The initial request to Azure Active Directory proceeds smoothly, allowing me to log in with my credentials. However, I anticipate that th ...

The Vue.js application is set up to only insert the `_id` value during a fetch post request, rather

I am encountering an issue with my Vue.js app where only the _id is being saved in my mongodb when I use a fetch request to post data to my API. In my Vue.js app, I have a method that includes a variable with JSON data which I am testing by making a fetch ...

What is the outcome of XmlHttpRequest.responseText?

I am new to JavaScript and looking to explore the potential of XMLHttpRequest.responseText with a specified URL. Can someone guide me on how to efficiently test this? let url = "http://m.google.com/"; <br> let xmlHttp = new XMLHttpRequest(); <br& ...

"Is there a way to retrieve "Lorem ipsum" information from a web service in JSON format

Does anyone know of any sample web services that serve JSON data? I'm looking to practice consuming JSON for testing and learning purposes. I would even be interested in downloading JSON files with images and other content to study offline. Perhaps th ...

Does the unique identifier of the element remain constant in jQuery?

For example: $("#savenew").live('click', function(e) { var user=<?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data:{user: user} , ...

What is the best way to toggle between two forms with JavaScript?

I have designed a login screen with two forms inside one div. The first form contains the login box, while the second form is for registration and is hidden using CSS with display:none;. Below the login button, there is a paragraph with an anchor tag to cl ...

I am interested in developing a select box with autocomplete functionality

Here is the HTML code I have: <select class="form-control" id="city" style="width:100%; margin-left:2%;"> <option>Sonal</option> <option>abcd</option> <option>3</option> <option& ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

Using JavaScript/JQuery to Access an External SQLite Database

Is there a way to incorporate my own SQLite database into a website using JavaScript and JQuery? I've searched for examples but have yet to find any helpful articles on the topic! ...