Skip to content

Instantly share code, notes, and snippets.

@SamirTalwar
Last active October 25, 2016 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamirTalwar/cdea07f38182887421ffc2e4fc5937fe to your computer and use it in GitHub Desktop.
Save SamirTalwar/cdea07f38182887421ffc2e4fc5937fe to your computer and use it in GitHub Desktop.
Implementations of functions that work on Promise arrays, including `all` and `race`.
const all = promises => {
if (promises.length === 0)
return Promise.resolve([])
let [head, ...tail] = promises
return head.then(h =>
all(tail).then(t =>
[h].concat(t)))
}
const allSuccessful = promises => {
if (promises.length === 0)
return Promise.resolve([])
let [head, ...tail] = promises
return head.then(h =>
allSuccessful(tail)
.then(
t => [h].concat(t)),
() => allSuccessful(tail))
}
const race = promises =>
new Promise((resolve, reject) =>
promises.forEach(promise =>
promise.then(resolve, reject)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment