![](/img/trans.png)
[英]Wait for each playStream() to finish before starting to read the next one
[英]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 循環不會在開始下一次迭代之前等待一次迭代完成。
我嘗試了幾種不同的解決方案,我在這里找到了嘗試使這個異步,包括:
像這樣:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.