等待每个 for 循环迭代完成,然后再开始 nodejs 中的下一个
Wait on each for loop iteration to finish before starting the next in nodejs
我有一个数组,其中的 URL 以逗号分隔。我似乎无法设法让循环在开始下一次之前完成每次迭代。
这是我的代码:
const options = {
method: 'post',
headers: {
'Authorization': 'Basic '+Buffer.from(`${user}:${password}`).toString('base64')
},
}
for (let url of urls.split(",")) {
console.log(url);
await axios.get(url, options)
.then(response => {
console.log(url);
<--Rest of my code-->
})
}
我可以看到第一个 console.log() 立即运行,因此 for 循环不会等待一个迭代完成再开始下一个迭代。
我已经尝试了在这里找到的几种不同的解决方案来尝试实现这种异步,包括:
- 将“for”循环更改为“for await”循环,这会导致保留关键字出现语法错误。
- 将 For 循环放入异步函数中。
像这样:
const calls = async (urls2) => {
for (let url of urls2.split(",")) {
await axios.get(url, options)
.then(response => {
console.log(url);
<--Rest of my code-->
})
}
}
calls(urls).catch(console.error);
我假设最后一个失败了,因为虽然函数是异步的,但它内部的所有内容仍然是同步的。
我只需要循环的每次迭代在下一次开始之前完成。
最简单的方法是什么?
const calls = async(urls2)=>{
for (let url of urls2.split(",")) {
const response = await axios.get(url,options); //will wait for response
console.log(response.data);
//rest of the code
}
}
我有一个数组,其中的 URL 以逗号分隔。我似乎无法设法让循环在开始下一次之前完成每次迭代。 这是我的代码:
const options = {
method: 'post',
headers: {
'Authorization': 'Basic '+Buffer.from(`${user}:${password}`).toString('base64')
},
}
for (let url of urls.split(",")) {
console.log(url);
await axios.get(url, options)
.then(response => {
console.log(url);
<--Rest of my code-->
})
}
我可以看到第一个 console.log() 立即运行,因此 for 循环不会等待一个迭代完成再开始下一个迭代。
我已经尝试了在这里找到的几种不同的解决方案来尝试实现这种异步,包括:
- 将“for”循环更改为“for await”循环,这会导致保留关键字出现语法错误。
- 将 For 循环放入异步函数中。
像这样:
const calls = async (urls2) => {
for (let url of urls2.split(",")) {
await axios.get(url, options)
.then(response => {
console.log(url);
<--Rest of my code-->
})
}
}
calls(urls).catch(console.error);
我假设最后一个失败了,因为虽然函数是异步的,但它内部的所有内容仍然是同步的。
我只需要循环的每次迭代在下一次开始之前完成。 最简单的方法是什么?
const calls = async(urls2)=>{
for (let url of urls2.split(",")) {
const response = await axios.get(url,options); //will wait for response
console.log(response.data);
//rest of the code
}
}