Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios.get().then() in a for loop

How would I go about running Axios in a for loop, each with a corresponding .then() function. Then after the for loop ends, run another function.

Example:

const array = ['asdf', 'foo', 'bar'];
let users = [];
for (i = 0; i < array.length; i++) {
  axios.get('/user/' + array[i].id).then(response => {
    // do something with response
    users.push(response);
  });
}

console.log(users);
like image 333
user1661677 Avatar asked Jun 10 '19 19:06

user1661677


People also ask

How do I loop through an Axios response?

Use async/await (promise) and for await for get data from for loop.

How use Axios get method?

A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios. get() . The get() method requires two parameters to be supplied to it.

What type does Axios get return?

When we send a request to a server, it returns a response. The Axios response object consists of: data - the payload returned from the server. status - the HTTP code returned from the server.

How do I use async await with Axios?

Axios Request With Async/AwaitYou start by specifying the caller function as async . Then use the await keyword with the function call. Due to the await keyword, the asynchronous function pauses until the promise is resolved.


2 Answers

const array = [{ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }]; // changed the input array a bit so that the `array[i].id` would actually work - obviously the asker's true array is more than some contrived strings
let users = [];
let promises = [];
for (i = 0; i < array.length; i++) {
  promises.push(
    axios.get('/user/' + array[i].id).then(response => {
      // do something with response
      users.push(response);
    })
  )
}

Promise.all(promises).then(() => console.log(users));

The .then() method of a Promise itself returns a Promise; so you can collect those and await all of them with Promise.all().

Note that even if you're doing this within an async function, you don't want to await inside the for-loop, because then each request will wait for the previous one to finish before it even starts, and presumably you want to run these requests in parallel.

Depending on your use case, a concise async / await function might look like this:

async function getMultiple(...objectsToGet) {
  let users = [];
  await Promise.all(objectsToGet.map(obj =>
    axios.get('/user/' + obj.id).then(response => {
      // do something with response
      users.push(response);
    })
  ));
  return users;
}

// some other async context
console.log(await getMultiple({ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }));
like image 137
Daniel Smedema Avatar answered Sep 19 '22 01:09

Daniel Smedema


You should collect all the promises inside an array and use promise.all in the following manner -

const array = ['asdf', 'foo', 'bar'];
let promises = [];
for (i = 0; i < array.length; i++) {
  promises.push(axios.get('/user/' + array[i].id))
}

Promise.all(promises)
  .then(responses => console.log(responses));
like image 33
Purvil Bambharolia Avatar answered Sep 17 '22 01:09

Purvil Bambharolia