Context:
- We need to send multiple requests using an asynchronous function
const urls = [
'https://www.first.com',
'https://www.second.com',
'https://www.third.com',
]
const handleAsyncRequest = async (url) {
// using fetch, axios, ...
}
- The simplest way is to use a loop to upload images one by one. This method takes a lot of time
for (let index = 0; index < urls.length; index++) {
await handleAsyncRequest(urls[index])
}
Solution:
-
In this post, I will show you how you can easily run async/await in parallel by using
Promise.all()
-
According to MDN Web Docs:
The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.
- Apply to our problem:
let requests = []
for (let index = 0; index < urls.length; index++) {
requests.push(
new Promise(async (resolve) => {
await handleAsyncRequest(urls[index])
resolve()
})
)
}
Promise.all(requests).then(results => {
// All data available here in the order of the elements in the array
});
- We can write more succinctly:
Promise.all(urls.map(handleAsyncRequest)).then(results => {
// All data available here in the order of the elements in the array
});