Promise All with Axios

2019-03-21 03:19发布

问题:

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

回答1:

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



回答2:

We defined a function ( getData ) to make API Call and it returns promise.

In Function (getAllData) URLPromises contains the array of promises which are returned from the getData function on Each invocation.

Here we waiting till all promises are resolved asynchronously {API respose}.

await Promise.all(URLPromises);

Response of above code will contain an array of response from API Call.

let URLs= ["https://www.something.com", "https://www.something2.com", "https://www.something3.com"]

async function getAllData(URLs){
  let URLPromises = URLs.map((URL)=>{
   return getData(URL);
  })
  let response = await Promise.all(URLPromises);
  console.log(response)
}

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



回答3:

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) => {
});



回答4:

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]);


回答5:

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)
  })