Skip to content

Instantly share code, notes, and snippets.

@scwood
Last active November 29, 2018 23:14
Show Gist options
  • Save scwood/399e6e248ca53276affec4729e710569 to your computer and use it in GitHub Desktop.
Save scwood/399e6e248ca53276affec4729e710569 to your computer and use it in GitHub Desktop.
Promise.all implementation
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