如何编写循环并向服务器发送请求,以便在收到上一个请求的响应后执行下一个请求?
我希望请求按顺序发送并按顺序显示结果:
for (item of [1,2,3]){
fetch(`http://test.com/users/${item}`).then((res)=>{
console.log(res.id) // I want the next request, to be send after received this reponse
})
}
最佳答案
使用等待标志。所以等待 fetch(...) 应该做到这一点
async function example() {
for (item of [1, 2, 3]) {
let res = await fetch(`http://test.com/users/${item}`);
console.log(res.id); // I want the next request, to be send after received this reponse
}
}
关于javascript - 如何在 JavaScript 中使用异步循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76790186/