In modern JavaScript development, handling asynchronous operations efficiently is essential, especially when multiple tasks need to run simultaneously. That’s where Promise.all comes in—a powerful method that allows you to execute several promises at once, waiting for all of them to resolve (or for one to reject) before proceeding. In this post, we’ll dive into how Promise.all works, why it’s such a valuable tool for managing concurrent asynchronous operations, and how you can implement it yourself to deepen your understanding of JavaScript promises.
Let’s get started!
Example usage
const p1 = Promise.resolve(1)
const p2 = Promise.resolve(2)
const p3 = Promise.resolve(3)
customPromiseAll([p1, p2, p3])
.then((res) => console.log(res))
.catch(console.error)
When we start writing the function, we’ll first define a variable named result to hold all the responses from the promises.
Then, we’ll return a new instance of Promise with resolve and reject.
function customPromiseAll(promises) {
let result = []
return new Promise((resolve, reject) => {
})
}
Now, we’ll iterate over the array of promises that the function receives using forEach, handling each resolved promise like this: each resolved promise will be inserted into the result array.
function customPromiseAll(promises) {
let result = []
return new Promise((resolve, reject) => {
promises.forEach((promise) => {
promise
.then((res) => {
result.push(res)
})
})
})
}
We’ll check an edge case: if the length of promises is equal to the length of result, then we will resolve with result.
function customPromiseAll(promises) {
let result = []
return new Promise((resolve, reject) => {
promises.forEach((promise) => {
promise
.then((res) => {
result.push(res)
if (result.length === promises.length) {
resolve(result)
}
})
})
})
}
Finally, we’ll add .catch in case any of the promises return an error.
function customPromiseAll(promises) {
let result = []
return new Promise((resolve, reject) => {
promises.forEach((promise) => {
promise
.then((res) => {
result.push(res)
if (result.length === promises.length) {
resolve(result)
}
})
.catch(reject)
})
})
}
Top comments (0)