Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

javascript - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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' }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...