Created
April 19, 2016 16:08
-
-
Save mfellner/041cf9500640d04abc3bf4e486e2927f to your computer and use it in GitHub Desktop.
Return the first resolved promise result or the last rejected error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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