Skip to content

Commit

Permalink
add promise-all-custom
Browse files Browse the repository at this point in the history
  • Loading branch information
emanuelefavero committed Mar 8, 2024
1 parent 4483e66 commit 084f48c
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions promise-all-custom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// * This is a custom implementation of the Promise.all method

function customPromiseAll(promises) {
return new Promise((resolve, reject) => {
if (promises.length === 0) {
resolve([])
return
}

const results = []
let completedPromises = 0

promises.forEach((promise, index) => {
Promise.resolve(promise)
.then((value) => {
results[index] = value
completedPromises++

if (completedPromises === promises.length) {
resolve(results)
}
})
.catch((error) => reject(error))
})
})
}

// ------------------------------------------------
// Usage

const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 1 resolved'), 200)
})

const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 2 resolved'), 300)
})

customPromiseAll([promise1, promise2]).then((values) => {
console.log(values)
})
// [ 'Promise 1 resolved', 'Promise 2 resolved']

0 comments on commit 084f48c

Please sign in to comment.