Promise All with Axios
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 Making a request with Axios inside Promise.all
I would suggest this structure that makes the .get()
and .put()
into a combined operation and then runs Promise.all()
once on the combined operations:
function someFunction() {
const corePath = `https://${conf.server.hostname}:${conf.server.port}/resource/${conf.version}`;
// return a promise that indicates when we're all done or had an error
return Promise.all(data.sequences.map(sequence => {
return axios.get(`${corePath}/${sequence}`, {
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer bbbbbbb'
}
}).then(data => {
return axios.put(`${corePath}/${sequenceName}`, data, {
headers: {
'Content-Type': 'application/json'
}
});
}).then(() => {
logger.debug(`Updating content : ${sequenceName}`);
}).catch(err => {
logger.error(`Error updating content`, err);
throw err;
});
});
}
Other notes:- Don't mix plain callbacks and promises. If you need to communicate back to some other code when this is done or has an error, then return your promise - don't use a callback.
- You don't show where
sequenceName
comes from. Your debug output makes it seem like it's something that varies by request, but it isn't defined anywhere in the code in your question. - If you want the promise this is returning resolve with some data, then return that value from the final
.then()
. Your question shows you calling a callback and passing itdata
, but doesn't show where that comes from.
Promise.all and building axios requests inside async function
This will make your Promise.all
resolve AFTER the catch inside the loop, or, indeed, after all the requests (successful or unsuccessful):
const axios = require('axios');
const someFunction = () => {
return new Promise(resolve => {
setTimeout(() => resolve('222'), 100)
})
}
const requestsData = ['https://httpstat.us/200', 'https://httpstat.us/205', 'https://httpstat.us/306']
const requestArr = requestsData.map(async data => {
let waitForThisData = await someFunction(data);
return axios.post(data)
.then(response => {})
.catch(error => console.log(error.toString()))
});
Promise.all(requestArr).then(() => {
console.log('resolved promise.all')
})
https://httpstat.us/306
will produce an erroneous call. You can try placing it anywhere within the requestsData
array. Promise.all vs Axios.all
The Axios documentation on NPM says that Axios.all()
is deprecated and you should use Promise.all()
in its place. I do not believe there is any intended difference between the two.
In fact, if you look in the current Axios source, you see this:
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
So, they are identical.I presume that Axios.all()
existed historically when Axios wanted to be able to run in environments that didn't have full native promise support so they were supplying promise functionality that might now be present.
Since all modern environments contain Promise.all()
, Axios.all()
is no longer necessary.
Related Topics
How to 'Await' on an Rx Observable
Why Is Window (And Unsafewindow) Not the Same from a Userscript as from a <Script> Tag
Why Are Exceptions Used for Rejecting Promises in Js
How to Create a Date Object from String in JavaScript
Load "Vanilla" JavaScript Libraries into Node.Js
Convert JavaScript Object or Array to JSON for Ajax Data
Why Do I Need to Await an Async Function When It Is Not Supposedly Returning a Promise
Angular 2 Router Event Listener
Jquery Attr('Checked','Checked') Works Only Once
Write Elements into a Child Iframe Using JavaScript or Jquery
Getting a Union of Two Arrays in JavaScript
Check If an Object Implements an Interface at Runtime with Typescript
Why Does If("String") Evaluate "String" as True But If ("String"==True) Does Not
How to Update a Specific Index from the Array in Firestore
Getusermedia() in Chrome 47 Without Using Https