0
我目前有一個異步API調用,此時使用異步&請求NPM包,在此刻向一個字符串端點發出了19個不同的請求。我剛剛發現,在我的請求結束時,返回的實際對象是先前請求的數據。下面是我的代碼示例:異步並行和請求包返回錯誤的API結果(NodeJS/Express)
router.get('/', function(req, res) {
async.parallel([
function(next) {
request(queryString + 'end point link', function(error, response, body) {
if (!error && response.statusCode == 200) {
var variable0 = JSON.parse(body);
return next(null, variable0);
};
console.log(error);
next(error);
});
},
function(next) {
request(queryString + 'end point link', function(error, response, body) {
if (!error && response.statusCode == 200) {
var variable19 = JSON.parse(body);
return next(null, variable19);
};
console.log(error);
next(error);
});
}],
function(err, results) {
res.render("view", {
variable0: results[0],
variable1: results[1],
variable2: results[2],
......
......
variable19: results[19]
});
});
});
這是完美的工作,直到我發現我的最後三個變量(讓我們稱之爲17,18和19)進行返回前API調用的結果。我不確定爲什麼會發生這種情況,任何建議都將不勝感激。
異步提供的結果變量是一個數組,我已將其修改爲適當請求的給定索引處的對象。