I’m working on a JavaScript project where I need to fetch data from multiple APIs asynchronously. Since each API call takes different amounts of time, I want to ensure that the final output array maintains the same order as the original API request sequence.
Problem:
- I need to make multiple asynchronous API calls in parallel to improve performance.
- The results must appear in the same order as the requests were made, even though each API takes a different time to respond.
For example, if I request data from three APIs in this order:
const urls = ['api/1', 'api/2', 'api/3'];
Even though api/2 may finish before api/1, the final output should still have the results in the order: ['result from api/1', 'result from api/2', 'result from api/3']
.
I attempted to use Promise.all()
to fetch the data:
const urls = ['api/1', 'api/2', 'api/3'];
const fetchData = async () => {
const promises = urls.map(url => fetch(url).then(response => response.json()));
const results = await Promise.all(promises);
console.log(results); // Results may come in a different order
};
fetchData();
This works for parallel execution, but the order of the results may not match the order of the URLs, since Promise.all()
resolves them as they finish, regardless of order.
I expect the output to match the request order, even though the requests finish at different times.