73

I just read an Article related to promise and was unable to comprehend how we can do multiple API call using Axios via Promise.all

So consider there are 3 URL, lets call it something like this

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

And an array in which we will store Value

  let promiseArray = []

Now, I want to run this in parallel (Promise.all), but I am unable to figure our how will we do it? Because axios have a promise in itself (or at-least that's how I have used it).

axios.get(URL).then((response) => {
}).catch((error) => {
})

Question: Can someone please tell me how we can we send multiple request using promise.all and axios

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 1
    https://stackoverflow.com/questions/37149466/axios-spread-with-unknown-number-of-callback-parameters seems similar to your question – Shyam Babu Oct 05 '18 at 18:01

8 Answers8

119

The axios.get() method will return a promise.

The Promise.all() requires an array of promises. For example:

Promise.all([promise1, promise2, promise3])

Well then...

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1);
const promise2 = axios.get(URL2);
const promise3 = axios.get(URL3);

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});

You might wonder how the response value of Promise.all() looks like. Well then, you could easily figure it out yourself by taking a quick look at this example:

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

thanksd
  • 54,176
  • 22
  • 157
  • 150
You Nguyen
  • 9,961
  • 4
  • 26
  • 52
27

fetchData(URL) function makes a network request and returns promise object with pending status.

Promise.all will wait till all promises are resolved or any promise is rejected. It returns a promise and resolve with array of responses.

let URLs= ["https://jsonplaceholder.typicode.com/posts/1", "https://jsonplaceholder.typicode.com/posts/2", "https://jsonplaceholder.typicode.com/posts/3"]

function getAllData(URLs){
  return Promise.all(URLs.map(fetchData));
}

function fetchData(URL) {
  return axios
    .get(URL)
    .then(function(response) {
      return {
        success: true,
        data: response.data
      };
    })
    .catch(function(error) {
      return { success: false };
    });
}

getAllData(URLs).then(resp=>{console.log(resp)}).catch(e=>{console.log(e)})
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Community
  • 1
  • 1
Mohammed Ashfaq
  • 3,353
  • 2
  • 15
  • 22
11

You still can use promise.all with array of promises passed to it and then wait for all of them to be resolved or one of them gets rejected.

let URL1 = "https://www.something.com";
let URL2 = "https://www.something1.com";
let URL3 = "https://www.something2.com";


const fetchURL = (url) => axios.get(url);

const promiseArray = [URL1, URL2, URL3].map(fetchURL);

Promise.all(promiseArray)
.then((data) => {
  data[0]; // first promise resolved 
  data[1];// second promise resolved 
})
.catch((err) => {
});
Tareq
  • 5,283
  • 2
  • 15
  • 18
9

Just to add to the approved answer axios also has its of Promise.all in the form axios.all it expects a list of promises and returns an array of responses.

let randomPromise = Promise.resolve(200);
axios.all([
    axios.get('http://some_url'),
    axios.get('http://another_url'),
    randomPromise
  ])
  .then((responses)=>{
    console.log(responses)
  })
Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24
9

Use Promise.allSettled which is almost same as Promise.all but it doesn't reject as a whole if any promise rejects. Promise.allSettled just waits for all promises to settle, regardless of the result.

const [ first, second, third ] = await Promise.allSettled([
  fetch('https://jsonplaceholder.typicode.com/todos/'),
  fetch('https://jsonplaceholder.typicode.com/todos/'),
  fetch('https://jsonplaceholder.typicodecomtodos')
])

// P.S: you can replace fetch with axios

The resulting array has:

  • { status:"fulfilled", value:result } for successful responses
  • { status:"rejected", reason:error } for errors.

enter image description here

norbekoff
  • 1,719
  • 1
  • 10
  • 21
8

Hope this may help

var axios = require('axios');
var url1 = axios.get('https://www.something.com').then(function(response){
    console.log(response.data)
  })
var url2 = axios.get('https://www.something2.com').then(function(response){
    console.log(response.data)
  })
var url3 = axios.get('https://www.something3.com').then(function(response){
    console.log(response.data)
  })

Promise.all([url1, url2, url3]).then(function(values){
  return values
}).catch(function(err){
  console.log(err);
})
Trouble106
  • 99
  • 1
  • 2
  • Similar code is in accepted answer (without `then` after `axios.get` and `catch` blocks) – barbsan Sep 06 '19 at 10:14
  • agree with @barbsan resolving each promise seperately is not the right way to handle. Promise.all effectively bundles a bunch of unresolved promise into a single unresolved promise that will resolve to an array of results. the Accepted answer is correct. – Michael Dausmann Nov 19 '20 at 03:29
  • Trouble106 this doesn't seem to be a right answer, your making individual get requests, promise.all is not required in your case. – Vasanth Sep 17 '21 at 15:57
2

Something like this should work:

const axios = require('axios');
function makeRequestsFromArray(arr) {
    let index = 0;
    function request() {
        return axios.get('http://localhost:3000/api/' + index).then(() => {
            index++;
            if (index >= arr.length) {
                return 'done'
            }
            return request();
        });

    }
    return request();
}

makeRequestsFromArray([0, 1, 2]);
sol404
  • 1,653
  • 13
  • 15
0
// using axios return
const promise0 = axios.get( url )
  .then( function( response ) {
    return response
  } )

// using function new promise
function promise1() {
  return new Promise( ( resolve, reject ) => {
    const promise1 = axios.get( url )
      .then( function( response ) {
        return response
      } )    
    resolve( promise1 )  
  ) }
}

Promise.all( [promise0, promise1()] ).then( function(results) {
  console.log(results[0]);
  console.log(results[1]);
});
antelove
  • 3,216
  • 26
  • 20