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

后端 未结 3 620
鱼传尺愫
鱼传尺愫 2020-12-28 10:24

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.

Exampl

相关标签:
3条回答
  • 2020-12-28 11:01

    If you are using a more recent version of javascript with async/await support, you can do the following:

    const array = ['asdf', 'foo', 'bar'];
    let users = [];
    for (const id in array) {
      const response = await axios('/user/' + id);
      users.push(response);
    }
    
    console.log(users);
    
    0 讨论(0)
  • 2020-12-28 11:03
    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 => {
          users.push(response);
        })
      ));
      return users;
    }
    
    // some other async context
    console.log(await getMultiple({ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }));
    
    0 讨论(0)
  • 2020-12-28 11:13

    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));
    
    0 讨论(0)
提交回复
热议问题