nodejs异步每个函数

时间:2015-07-13 00:54:01

标签: javascript arrays node.js asynchronous callback

在节点js中,我使用异步函数从另一个函数获取结果并将其存储为数组并返回结果。但在这里我得到空的json作为输出{}。查看代码块内的注释。我可以知道我在哪里做错了吗?

collectSearchResult: function (searchConfig, callback) {
var searchResult = {};
async.each(searchConfig.scope, function (scope, callback) {
  var query = {
        "query": {
           "match": {
           "_all": searchConfig.q
         }
      },
     operationPath = scope.url;

    this.doSearch(operationPath, query, function (err, results) {
        var type = scope.type;
        searchResult[type] = results;

        // Here i am able to get correct output async
        console.log(searchResult);
    });

    callback();
  }.bind(this), function (err) {

    // Here it is just returning empty json like {}. this function is called before this.doSearch complete its task
    console.log(searchResult);
    callback(err, searchResult);
  });
}

1 个答案:

答案 0 :(得分:0)

collectSearchResult: function (searchConfig, callback) {
var searchResult = {};
async.each(searchConfig.scope, function (scope, callback) {
var query = {
    "query": {
       "match": {
       "_all": searchConfig.q
     }
  },
 operationPath = scope.url;

this.doSearch(operationPath, query, function (err, results) {
    var type = scope.type;
    searchResult[type] = results;

    // Here i am able to get correct output async
    console.log(searchResult);
    //<><><><><><><>
    callback(); //you need to place the callback for asynch.each 
    //within the callback chain of your query, else async.each
    //immediately finishes before your data has arrived.
    //<><><><><><><>
});


}.bind(this), function (err) {

// Here it is just returning empty json like {}. this function is called before this.doSearch complete its task
console.log(searchResult);
callback(err, searchResult);
});
}