Last active
May 13, 2020 08:57
-
-
Save nc7s/5a6033f88a7d9ab456826ad37103a64b to your computer and use it in GitHub Desktop.
Implement Promise.all by hand.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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