Dev5
Dev5

Reputation: 459

Javascript await inside a loop

I am trying to work with an api where I have to send a request for each item in a list. However, I see that the loop doesn't seem to wait for every request, i.e, the loop doesn't work as expected. Here's the code below

getInfo = async () => {
   const mylist = ["item1","item2","item3","item4","item5","item6","item7"]
   const responses = []
   const len = mylist.length
   for (let i = 0; i < len; i++) {
      //console.log("inside loop")
      await axios.get("some_url/"+mylist[i])
          .then(res => {
              responses.push(res.data)
          })
   }

When I run the program, all the console.log("inside loop") executes immediately without waiting for the request to be complete.

How can I modify the code so as to wait for each response to be completed before updating the for loop counter variable?

Upvotes: 2

Views: 2404

Answers (2)

Marcus Ilgner
Marcus Ilgner

Reputation: 7231

Internally, await is translated into a Promise chain. Since the for loop can't be transformed into a Promise-continuation, you'll need to convert it to a Promise-based construct.

Depending on what you want to achieve there are multiple ways to go about it. Constructing the responses array could be done with a map statement.

const promises = mylist.map(item => {
   return axios.get("some_url/"+item).then(res => { return res.data; })
});
const data = await Promise.all(promises);

No manual pushing items around or fiddling with the array length.

Upvotes: 3

Tibebes. M
Tibebes. M

Reputation: 7548

You could try re-arranging the code to something like this. But using a Promise.all with Array.prototype.map would be more idiomatic solution for the problem.

await the async call (remove unnecessary .then call) and then console.log

getInfo = async () => {
   const mylist = ["item1","item2","item3","item4","item5","item6","item7"]
   const responses = []
   const len = mylist.length
   for (let i = 0; i < len; i++) {
      responses.push((await axios.get("some_url/"+mylist[i])).data)
      console.log("inside loop")
   }
}

Upvotes: 3

Related Questions