0

What is the better way to handle the loop in node.js? For example, in the below code I am inserting the value into the new array. But the way I am returning the Promise seems to be an incorrect way to handle the loop, so is their any better option to do this?

let userProfileScore = [];
return new Promise(function (resolve, reject) {
    for (let i = 0; i < userArr.length; i++) {
        user.userProfile(userArr[i], (err, score) => {
            if (err) throw err;
            userProfileScore.push({
                userID: userArr[i],
                value: sco
            });
            if (i == userArr.length - 1) {  // Here I am checking the key and then resolving the promise .
                resolve(userProfileScore);
            }
        });
    }
});
NayoR
  • 702
  • 6
  • 13
Sonu
  • 29
  • 7
  • Possible duplicate of [Asynchronous Process inside a javascript for loop](https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) – laggingreflex Apr 16 '18 at 10:04
  • I would create an array of promises via the loop and then straight afterwards run Promise.all(promises). Where promises is the array of promises – Freddie Apr 16 '18 at 11:15

1 Answers1

0

You can use Promise.all to process a list of promises created in your callbacks, this is one way to handle calling a list of asynchronous functions:

let promiseList = userArr.map((userObj) => {
    return new Promise((resolve, reject) => {
        user.userProfile(userObj, (err, score) => {
            if (err) {
                reject(err);
            } else {
                resolve({ userID: userObj, value: score});
            }
        })
    })
});

Promise.all(promiseList).then((result) => {
   console.log(result);
}).catch ((err) => {
   console.error(err);
})
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40