node.js中的异步性质

时间:2015-03-04 06:23:28

标签: javascript node.js asynchronous

我是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为空。

我必须让一切都同步。请分享您的想法。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用asola.js的caolan?链接: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');
    }
});