Skip to content

Instantly share code, notes, and snippets.

@lkchoi
Created August 13, 2018 18:42
Show Gist options
  • Select an option

  • Save lkchoi/ac60eb67fcbf70b55da9ddc8f351116e to your computer and use it in GitHub Desktop.

Select an option

Save lkchoi/ac60eb67fcbf70b55da9ddc8f351116e to your computer and use it in GitHub Desktop.
Util function to return the result of the first Promise to resolve
function firstResolved (promises) {
// https://stackoverflow.com/a/37235274
// This is a classic example where inverting your logic makes it much clearer.
// Your "race" in this case is that you want your rejection behavior to in
// fact be success behavior.
// If a request fails, count that as a resolution so it will keep waiting
// for other possible successes. If a request succeeds, treat it as a
// rejection so Promise.all immediately bails out.
promises = promises.map(p => p.then(
val => Promise.reject(val),
err => Promise.resolve(err)
));
return Promise.all(promises).then(
// If '.all' resolved, we've just got an array of errors.
errors => Promise.reject(errors),
// If '.all' rejected, we've got the result we wanted.
val => Promise.resolve(val)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment