我是node.js的新手,我不知道如何解决这个问题。由于 Node.js 是异步性质的,我无法以结构化方式预测结果......
我的场景如下:
aysnc.foreach(Object.keys(req.body), function(elem){
if(elem !== aaaa){
client.search(Query).then(function(Data){
//----------> For every query is a callback, so after
// sending the result to front-end this callback is returning.
// I have to make this query executed and return result and
// after that only the next loop should start.
//some logic here
arr1;-------------->populating result for each query
});
} else {
aysnc.foreach(Object.keys(req.body.xxxx), function(elem){
client.search(Query).then(function(Data){
//some logic here
arr2;
});
});
}); 最后我要做的是:
if(--Object.keys(req.body).length === 0){
intersect arr1 an arr2
}
我必须使 arr1 和 arr2 相交。但在填充 arr1 和 arr2 之前,异步性质完成了循环,并且 arr1 和 arr2 为空。
我必须让一切同步。请分享您的想法。提前致谢。
最佳答案
您尝试过使用caolan的async.js吗?链接:https://github.com/caolan/async
尝试这样的事情。
var counter = 0;
var arr1 = [];
async.each(Object.keys(req.body), function(elem, callback) {
//checks if counter, if equal callback to send the total
if(counter == req.body.length) {
callback(null, arr1);
} else {
//do your query here
// put your if else here
counter++;
if(elem == null) {
//call callback for error
callback('error elem is null', null)
}
}
}, function(err, total){
if( err ) {
res.send(400);
} else {
res.send(200);
//you will see the the combined array here
console.log(total);
console.log('processed successfully');
}
});
关于javascript - Node.js 中的异步性质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28847875/