简体   繁体   中英

Wait on each for loop iteration to finish before starting the next in nodejs

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:

  1. Changing the "for" loop to a "for await" loop, which caused a syntax error for a reserved keyword.
  2. Putting the For loop in an async function.

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?

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
   }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM