Skip to content

Instantly share code, notes, and snippets.

@mfellner
Created April 19, 2016 16:08
Show Gist options
  • Save mfellner/041cf9500640d04abc3bf4e486e2927f to your computer and use it in GitHub Desktop.
Save mfellner/041cf9500640d04abc3bf4e486e2927f to your computer and use it in GitHub Desktop.
Return the first resolved promise result or the last rejected error
function promiseFirst(promises) {
function tryResolve([x, ...xs], resolve, reject) {
if (xs.length > 0)
x.then(resolve).catch(_ => tryResolve(xs, resolve, reject))
else
x.then(resolve).catch(reject)
}
return new Promise((resolve, reject) =>
tryResolve(promises, resolve, reject)
)
}
const promises = [Promise.reject(0),
Promise.resolve(1),
Promise.reject(0)]
promiseFirst(promises).then(console.log)
.catch(e => console.error('Error:', e))
// == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment