如何等待循环节点完成执行.js



>我有这样一个循环:

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

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

这将导致来自cursor.all()的平面keys数组

任何失败的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
})

你需要使用 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.all((来等待所有承诺解析,然后你可以访问结果的结果

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

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

最新更新