Created
August 14, 2019 08:51
-
-
Save libook/7a9743cadc14fa4821802c12b523be2e to your computer and use it in GitHub Desktop.
Polyfill of Promise.any
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
/** | |
* Polyfill of Promise.any | |
* @param {Promise[]} promiseList | |
* @returns {Promise<Object>} - First fulfilled result form one of promiseList. | |
* @throws {Error} - Provide mixed error message and errors property. | |
*/ | |
const promiseAny = async (promiseList) => { | |
return Promise.all(promiseList.map(promise => { | |
return promise.then( | |
value => { | |
throw value; | |
}, | |
error => error, | |
); | |
})).then( | |
(errorList) => { | |
const mixedError = new Error( | |
errorList.reduce( | |
(message, error) => { | |
return message += `\n` + error.message; | |
}, | |
'Mixed Error: ', | |
), | |
); | |
mixedError.errors = errorList; | |
throw mixedError; | |
}, | |
result => result, | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment