我有一個for
循環,我想在每次迭代時調用一個異步函數。但我得到一個JS堆棧跟蹤錯誤。以下是我的代碼的原型。我也使用了IIFE模式,但它不起作用。在for循環中調用JavaScript異步函數
for(let i = 0; i<99999;i++){
getData(i, function(err, result){
if(err) return err;
else{
console.log(result);
}
});
}
function getData(number, callback){
request('http://someapiurl'+number, function(err, response){
if(err) callback(err, null);
else{
callback(null, response)
}
})
}
如果您想在執行循環的下一次迭代之前等待getData的結果,則不能使用for循環。 –