In order to get the results in the same order, you can simply use Promise.all
, or axios.all
, but this will executes all the requests in parallel:
const array = [ '1', '2', '3', '4', '5' ];
axios.all(array.map(el => () => axios.get(`/item/${el}`))).then(data => console.log(data));
But, if you need to perform them in order, so sequentially, because maybe in the second request you need to access the response of the first one, you have to chain every next request in the then
of the previous one:
const array = [ '1', '2', '3', '4', '5' ];
const requests = array.map(el => () => axios.get(`/item/${el}`));
requests[0]().then(data1 => {
requests[1]().then(data2 => { ... });
});
Or if you want to avoid the hell of callbacks return the promises and then chai the then
blocks:
const array = [ '1', '2', '3', '4', '5' ];
const requests = array.map(el => () => axios.get(`/item/${el}`));
requests[0]()
.then(data1 => requests[1]())
.then(data2 => { ... });
Or you can use async/await
:
const array = ['1', '2', '3', '4', '5'];
const requests = array.map(el => () => axios.get(`/item/${el}`));
async function performRequests() {
const res1 = await requests[0]();
const res2 = await requests[1]();
}
performRequests();