Last active
October 18, 2022 11:37
-
-
Save luan0ap/967ba2528f22fb72a64c14a3c82e9a59 to your computer and use it in GitHub Desktop.
My polyfill implementation of Promise.all
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 promiseAll (promises = []) { | |
return new Promise((resolve, reject) => { | |
let result = [] | |
let resolvedPromisesCount = 0 | |
const handle = (index, data) => { | |
if (data instanceof Error) { | |
return reject(data) | |
} | |
result[index] = data | |
resolvedPromisesCount++ | |
if (promises.length === resolvedPromisesCount) { | |
return resolve(result) | |
} | |
} | |
const isIterable = (obj) => { | |
if (obj === null || obj === undefined) { | |
return false | |
} | |
return typeof obj[Symbol.iterator] === 'function' | |
} | |
if (!isIterable(promises)) { | |
return reject(new TypeError(`${typeof promises} ${promises} is not iterable`)) | |
} | |
if (promises?.length === 0) { | |
return resolve(result) | |
} | |
for (const index in promises) { | |
const promise = promises[index] | |
if (promise instanceof Promise) { | |
promise | |
.then(data => handle(index, data)) | |
.catch(err => handle(index, err)) | |
} else { | |
handle(index, promise) | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment