我对 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。或者,您可以使用for 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
提交
取消