如何等待循环Node.js的完整执行

时间:2017-08-06 08:17:28

标签: javascript node.js asynchronous

我有这样一个循环:

var someArray = [];

for(var i = 0; i < myArray.length; i++) {
    var tempArray = [];

    arangodb.query('somequery')
        .then(
            cursor => cursor.all()
        ).then(
            keys => tempArray  = keys,
            err => console.error('Failed to execute query:', err)
        ).then(function () {
            someArray.push.apply(someArray, tempArray);
        });
} 

我希望在tempArrays收集所有someArray时执行其他操作。但由于Node.js是异步的,我不知道该怎么做。你能帮帮我吗?提前致谢。

3 个答案:

答案 0 :(得分:3)

这将导致来自keys

cursor.all()平面数组

任何失败的arangodb.query都将被忽略(尽管仍然使用控制台输出)

Promise.all(myArray.map(item => 
    arangodb.query('somequery')
    .then(cursor => cursor.all()))
    .catch(err => console.error('Failed to execute query:', err))
)
// remove rejections, which will be undefined
.then(results => results.filter(result => !!result))
// flatten the results
.then(results => [].concat(...results))
.then(results => {
    // do things with the array of results
})

答案 1 :(得分:1)

您需要使用Promise.all()

var someArray = [];

function queryDB(){
    return arangodb.query('somequery')
        .then(
            cursor => cursor.all()).then(
            keys => tempArray  = keys,
            err => console.error('Failed to execute query:', err)
         ).catch(function(err){
            console.log('Failed');
         })
}
var promiseArray = [];
for(var i = 0; i < myArray.length; i++)
{
   promiseArray.push(queryDB());
} 

Promise.all(promiseArray).then(function(results){

    someArray = results.filter(result => !!result);
})

基本上queryDB()会返回一个promise,你可以做Promise.all()等待所有promises解析然后你可以访问结果中的结果

答案 2 :(得分:1)

跟踪所有异步操作是否完成的唯一方法是简单地保留成功回调触发器和失败回调触发器的计数。以下应该可以帮到你。

let count = 0;

const checkCompletion = (curr, total) => {
    if (curr < total) {
        // Not all tasks finised
    } else {
        // All done
    }
};

for(var i = 0; i < myArray.length; i++) {
    var   tempArray = [];
    arangodb.query('somequery')
        .then(cursor => cursor.all())
        .then(keys => {
            // success
            count += 1;
            checkCompletion(count, myArray.length);
        }).catch(e => {
            // failure
            count += 1;
            checkCompletion(count, myArray.length);
        });

}