What is the best way to handle responses from several asynchronous calls?

Looking for advice on handling asynchronous calls within a loop, similar to the question addressed here. The key difference is that in this scenario, the asynchronous function is called multiple times within a loop.

The challenge lies in returning the value of 's'. Currently, the code returns undefined. This function is invoked within a for loop and utilizes the Bookshelfjs ORM library. Any suggestions or tips would be greatly appreciated!

function getUsernameFromDBAsync(userId) {
    var s = "moo";

    new Model.Users({
            idUser: userId
        })
        .fetch()
        .then(function(u) {
            var prenom = u.get('firstName');
            var nom = u.get('familyName');
            s = prenom + " " + nom;
            return s;
        });
}

Answer №1

You're not really providing a clear example of how you're running the loop, so it's a bit difficult to suggest what to do. Assuming that .fetch().then() returns a promise, here's a basic idea using standard ES6 promises in node.js:

function getUsernameFromDBAsync(userId) {
    var s = "moo";

    return new Model.Users({
        idUser: userId
    }).fetch().then(function (u) {
        var firstName = u.get('firstName');
        var familyName = u.get('familyName');
        s = firstName + " " + familyName;
        return s;
    });
}

var userIds = [...];
var promises = [];
for (var i = 0; i < userIds.length; i++) {
    promises.push(getUsernameFromDBAsync(userIds[i]));
}

// set up a .then() handler for when all promises are completed
Promise.all(promises).then(function(names) {
    // handle names array here
}, function(err) {
    // handle error here
});

If you are using the Bluebird promise library, you can simplify it like this:

function getUsernameFromDBAsync(userId) {
    var s = "moo";

    return new Model.Users({
        idUser: userId
    }).fetch().then(function (u) {
        var firstName = u.get('firstName');
        var familyName = u.get('familyName');
        s = firstName + " " + familyName;
        return s;
    });
}

var userIds = [...];
Promise.map(userIds, getUsernameFromDbAsync).then(function(names) {
    // handle names array here
}, function(err) {
    // handle error here
});

Answer №2

It is unnecessary to use variable s. You can simply return the concatenated "first name last name" string from the success callback of the function.

function fetchUserNameFromDatabaseAsync(userId) {
    return new Model.Users({
        idUser: userId
    }).fetch().then(function (user) {
        return user.get('firstName') + ' ' + user.get('familyName');
    });
}

To handle your "loop", you can utilize Array.prototype.map() to create an array of promises. Follow this by using Promise.all(promises).then(...) to receive and process an array of names once all promises are resolved.

var promiseArray = userIds.map(function(userId) {
    return fetchUserNameFromDatabaseAsync(userId);
});
Promise.all(promiseArray).then(function(names) {
    // Perform actions with `names`, which contains an array of 'first name last name' strings.
}, function(error) {
    // Handle errors, for example ...
    console.error(error);
});

An even more concise approach:

Promise.all(userIds.map(fetchUserNameFromDatabaseAsync)).then(function(names) {
    // Perform actions with `names`, an array of 'first name last name' strings.
}, function(err) {
    // Handle errors, for example ...
    console.error(err);
});

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

Achieve iframe resizing using only pure JavaScript, no reliance on jQuery required

I have a question about an iframe on my webpage. <iframe class="myframe" src="some_page.html" width="800px" height="600px" /> Is there a way to make this iframe resizable like the <textarea></textarea> tag? I prefer to achieve this wit ...

What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code: $(&apos ...

Error: The function 'addToCart' is not defined in React.js

My website features a page showcasing various products that users can add to their cart. However, upon integrating the backend with asp.net core on the product page, I encountered an issue with the "add to cart" button not functioning properly on the Produ ...

Unveil the power of the "Enter" key with these jQuery hacks

Is there a way to prevent the Enter key from being counted as a character when disabling the submit button until something is entered in a TextArea? This functionality is achieved using the Count.js.coffee script. $(document).ready -> $(".cmnt_btn") ...

How to add texture to a three.js element

I'm struggling to properly apply a texture to an object I exported. Here is the code I have: var loader = new THREE.ObjectLoader(); var texture = THREE.ImageUtils.loadTexture('models/mountain/mountain.png'); loader.load("models/mountain/mo ...

I am seeking a way to eliminate double quotation marks from a string without using the replace function

I need assistance in removing double quotes from the string "Hello". I have an array var ary = ['a', 'b' , 'c'] When I extract a value from the array, it returns the value in string format, such as ary[0] = "a", but I want i ...

Is there a way to access the value variable from a JavaScript file located in the javascript folder and bring it to the routes/index.js file in a Node.js and Express application?

I'm currently working on transferring the input value from an HTML search box to the index route file in Node.js using Express. I have successfully retrieved the value from the search box in the javascript/javascript.js file, and now my objective is t ...

Function is not triggered in React component

When the LoginPage calls AuthForm, the structure is as follows: function mapDispatchToProps(dispatch: Redux.Dispatch<any>) { return { signUpWithEmail: function(email: string, password: string) { // bla bla }, }; } handleForm ...

Is there a way to make elasticX() and elasticY() only affect the upper bound in dc.js?

One question I have regarding my bubbleChart in dc.js is related to the x-axis. I want the count on the x-axis to always start at 0, but have an upper bound that adjusts based on the range I am looking at. Currently, when I use .elasticX(true), both the up ...

When a button on a form is disabled using form.submit, it will not be included in the data that is

I have implemented a code on a page that locates every submit button, finds the form it belongs to, and adds a listener. This listener disables the button for a few seconds in order to prevent accidental duplicate submissions of the form. <input type=" ...

The nodejs events function is being triggered repeatedly

I have been developing a CMS on nodejs which can be found at this link. I have incorporated some event hooks, such as: mpObj.emit('MP:FOOTER', '<center>MPTEST Plugin loaded successfully.</center>'); Whenever I handle this ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

What is the best way to display the next and restart buttons at the bottom of every question?

How can I display the next and restart buttons at the bottom of each question in my JavaScript quiz web app? Why is the user unable to choose the wrong answer from the provided options? I'm facing difficulty showing the next and restart buttons for i ...

Challenges encountered with the "load" event handler when creating a Firefox Extension

I am currently troubleshooting a user interaction issue with my Firefox extension. The tasks that my extension needs to complete include: Checking certain structures on the currently viewed browser tab Making backend server calls Opening dialogs Redirect ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

In order to properly set up an AutoNumeric object, it is essential to have at least one valid parameter provided

I've been working with the AutoNumeric library in my Vue js V2 application and keep encountering a specific error message in the console Issue with mounted hook: "Error: At least one valid parameter is needed to initialize an AutoNumeric object& ...

What is the best way to showcase a JSON array in a tabular layout?

I have a JSON array structured like this: [ { id: "001", name: "apple", category: "fruit", color: "red" }, { id: "002", name: "melon", category: "fruit", color: "green" }, ...

AngularJS directive not registering event after model update

Within my angularjs application, I have implemented an element directive that is equipped with an event listener. This listener is designed to respond to a broadcast event from the controller. app.directive('listItem', function(){ return { ...

I'm facing an issue with binding keyboard events in Vue - any suggestions on how to resolve

Hello everyone! I'm a newcomer to the world of Vue. Recently, I encountered an issue with keyboard-event binding that has left me puzzled. Let me share the relevant code snippet below: ...other code... <template v-for="(ite ...

Verify the input in text fields and checkboxes using JavaScript

I'm in the process of creating a complete "validate-form" function, but there are still a couple of things missing: Ensuring that the Name field only allows alphabetical characters and white spaces Validating that at least one checkbox is selected, ...