1
我有這樣的陣列REST的API的路徑:使用異步與http.get,節點JS
var paths = ['path1','path2','path3'];
我想創建與來自每個路徑的結果的數組。在這種情況下,我改用「http://www.google.com/index.html」而不是「路徑」
exports.test = function(req, res){
var paths = ['path1','path2','path3'];
var resultArr = [];
async.each(paths, function(path, cb){
console.log('collecting data from: ' + path);
http.get('http://www.google.com/index.html', function(result){
resultArr.push(result);
console.log('Done collecting data from: ' + path);
cb();
});
}, function(){
console.log('Done collecting data from all paths');
res.status(200).send('hello');
});
};
這將記錄:
Starting server at 127.0.0.1:5000
collecting data from: path1
collecting data from: path2
collecting data from: path3
Done collecting data from: path2
Done collecting data from: path1
Done collecting data from: path3
Done collecting data from all paths
GET /test 304 128.752 ms - -
它不等待調用完成。我想要一個接一個地看到結果。我究竟做錯了什麼?
你的代碼的行爲正確,你有什麼期待發生在這裏? – Cyrbil
「請注意,由於此函數並行地將迭代器應用於每個項目,因此不能保證迭代器函數將按順序完成。」 - https://www.npmjs.com/package/async#each – TAGraves