Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Last active October 18, 2022 11:37
Show Gist options
  • Save luan0ap/967ba2528f22fb72a64c14a3c82e9a59 to your computer and use it in GitHub Desktop.
Save luan0ap/967ba2528f22fb72a64c14a3c82e9a59 to your computer and use it in GitHub Desktop.
My polyfill implementation of Promise.all
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