Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何处理节点js中的异步for循环_Node.js_For Loop_Ecmascript 6_Es6 Promise - Fatal编程技术网

Node.js 如何处理节点js中的异步for循环

Node.js 如何处理节点js中的异步for循环,node.js,for-loop,ecmascript-6,es6-promise,Node.js,For Loop,Ecmascript 6,Es6 Promise,在node.js中处理循环的更好方法是什么?例如,在下面的代码中,我将值插入到新数组中。但是我返回承诺的方式似乎是处理循环的错误方式,那么他们有更好的选择吗 let userProfileScore = []; return new Promise(function (resolve, reject) { for (let i = 0; i < userArr.length; i++) { user.userProfile(userArr[i], (err, sco

在node.js中处理循环的更好方法是什么?例如,在下面的代码中,我将值插入到新数组中。但是我返回承诺的方式似乎是处理循环的错误方式,那么他们有更好的选择吗

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);
            }
        });
    }
});
让userProfileScore=[];
返回新承诺(功能(解决、拒绝){
for(设i=0;i{
如果(错误)抛出错误;
userProfileScore.push({
userID:userArr[i],
价值:上海合作组织
});
如果(i==userArr.length-1){//这里我检查密钥,然后解析承诺。
解析(userProfileScore);
}
});
}
});

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

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

我可能会通过循环创建一个承诺数组,然后直接运行Promise.all(承诺)。承诺就是一系列的承诺