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);
});
}
你爲什麼要使用綁定所有的地方?你試圖用這個函數做什麼?看起來你只是想運行一個查詢並在回調中返回一個結果。 – mmilleruva
刪除了不必要的綁定。 searchConfig.scope是配置數組。我打電話異步從另一個函數this.doSearch獲取數據,這有助於從服務器獲取數據。 –
這裏是功能 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}, –