2015-07-13 107 views
0

在節點JS,我使用異步函數來獲取從另一個函數的結果並將其存儲爲陣列,並返回結果。但在這裏我得到空json作爲輸出{}。查看代碼塊中的註釋。我可以知道我在哪裏犯錯嗎?異步的NodeJS每個功能

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

你爲什麼要使用綁定所有的地方?你試圖用這個函數做什麼?看起來你只是想運行一個查詢並在回調中返回一個結果。 – mmilleruva

+0

刪除了不必要的綁定。 searchConfig.scope是配置數組。我打電話異步從另一個函數this.doSearch獲取數據,這有助於從服務器獲取數據。 –

+0

這裏是功能 doSearch:功能(operationPath,查詢,回調){ \t \t request.post({ \t \t \t網址:使用rootUrl + operationPath, \t \t \t標題:{ \t \t \t \t「內容型「: 」應用/ JSON「, \t \t \t}, \t \t \t體:JSON.stringify(查詢) \t \t},功能(ERR,響應){ \t \t \t變種信息搜索結果= response.body; \t \t \t回調(ERR,信息搜索結果); \t \t}); \t}, –

回答

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

非常感謝Hatt現在可以工作。 –