至尊寶的傳說
2023-10-14 15:43:10
我對 Axios 和 foreach 循環有疑問。我的 Api 提供程序僅支持 5 個同時調用,因此我想一一調用,但是當執行此代碼時,每個主體不等待完成調用函數并收到錯誤代碼 429。如何解決此問題?謝謝。async function call(url) { var options = { method: 'GET', url: url, auth: { username: '*****', password: '*****' } }; var response = await axios.request(options); print(response.data["Id"])}app.get('/save', async (req, res) => { var options = { method: 'GET', url: 'getListUser', auth: { username: '***', password: '***' } }; var response = await axios.request(options); response.data["users"].forEach( async (val) => { console.log("ENTER"); var url = 'getDetailUser' + val["id"]; var res = await call(url); // <- How to wait finish this? console.log("EXIT") }, (err) => { console.log(err) }) res.status(200).send("ok").end();});
3 回答

呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
僅供參考,Promise無法使用涉及回調的循環,即forEach?;蛘撸梢允褂胒or of
try {
for (const val of response.data['users']) {
console.log("ENTER");
var url = 'getDetailUser' + val["id"];
var res = await call(url);
console.log("EXIT")
}
} catch (error) {
console.log(error)
}

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
只需稍作改動
await Promise.allSettled(response.data["users"].map(val => {
? ?var url = 'getDetailUser' + val["id"];
? ?return call(url);?
}))

慕容3067478
TA貢獻1773條經驗 獲得超3個贊
Promise.all() 就是這樣
await Promise.all(response.data["users"].map(val => {
var url = 'getDetailUser' + val["id"];
return call(url);
}))
添加回答
舉報
0/150
提交
取消