Skip to content

Instantly share code, notes, and snippets.

@nc7s
Last active May 13, 2020 08:57
Show Gist options
  • Save nc7s/5a6033f88a7d9ab456826ad37103a64b to your computer and use it in GitHub Desktop.
Save nc7s/5a6033f88a7d9ab456826ad37103a64b to your computer and use it in GitHub Desktop.
Implement Promise.all by hand.
function promiseAll(promises) {
return new Promise((resolve, reject) => {
let results = [],
position = 0,
fulfilled = 0,
resolved = false
for(let promise of promises) {
let promisePosition = position
if(promise instanceof Promise) {
promise.then(value => {
results[promisePosition] = value
fulfilled++
if(!resolved && fulfilled == promises.length) {
resolved = true
resolve(results)
}
}, reason => reject(reason))
} else {
results[promisePosition] = promise
fulfilled++
}
position++
}
/* 1. `promises` is empty, or
* 2. `promises` contains no Promises.
**/
if(position == 0 || fulfilled == position) {
resolve(results)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment