如何处理节点js中的async for循环

时间:2018-04-16 09:36:47

标签: node.js for-loop ecmascript-6 es6-promise

在node.js中处理循环的更好方法是什么?例如,在下面的代码中,我将值插入到新数组中。但是我返回Promise的方式似乎是处理循环的一种不正确的方法,所以他们有更好的选择吗?

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);
            }
        });
    }
});

1 个答案:

答案 0 :(得分:0)

您可以使用Promise.all来处理回调中创建的promise列表,这是处理异步函数列表的一种方法:

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);
})
相关问题