Last active
November 29, 2018 23:14
-
-
Save scwood/399e6e248ca53276affec4729e710569 to your computer and use it in GitHub Desktop.
Promise.all implementation
This file contains hidden or 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 all(promises) { | |
return new Promise((resolve, reject) => { | |
if (!isIterable(promises)) { | |
reject(new TypeError(`${promises} is not iterable`)) | |
return | |
} | |
const promisesArray = [...promises] | |
if (promisesArray.length === 0) { | |
resolve([]) | |
return | |
} | |
const results = [] | |
let numberOfResolved = 0 | |
promisesArray.forEach((promise, i) => { | |
Promise.resolve(promise) | |
.then((value) => { | |
results[i] = value | |
numberOfResolved++ | |
if (numberOfResolved === promisesArray.length) { | |
resolve(results) | |
} | |
}) | |
.catch(reject) | |
}) | |
}) | |
} | |
function isIterable(item) { | |
return typeof item[Symbol.iterator] === 'function' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment