Reputation: 819
I have an array with URLs separated by a comma. I can't seem to manage to get the loop to finish each iteration before starting the next. This is my code:
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-->
})
}
I can see that the first console.log() runs at once, so the for loop is not waiting for one iteration to finish before starting the next.
I have tried several different solutions I found here to try and make this async, including:
like this:
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);
I assume this last one failed because, while the function is async, everything inside of it is still synchronous.
All I need is for each iteration of the loop to finish before the next one starts. What is the simplest way to do this?
Upvotes: 0
Views: 2068
Reputation: 1315
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
}
}
Upvotes: 1