Promise All with Axios
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) => {
});
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)
})
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>
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