Skip to content

Instantly share code, notes, and snippets.

@johnpaulada
Last active May 10, 2018 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 johnpaulada/fe5532f49f10f3579d2b337667aee73e to your computer and use it in GitHub Desktop.
Save johnpaulada/fe5532f49f10f3579d2b337667aee73e to your computer and use it in GitHub Desktop.
When you need Promise.all() but you want it to resolve even if an item rejects.

Promise.notAll

Used when you need Promise.all() but you want it to resolve to an array even if an item rejects.


Assume we have Promises a, b, and c. Also assume that b rejects with an Error.

With await Promise.all([a, b, c]), will throw an Error.

With await Promise.notAll([a, b, c]), the result would be an array like: [resultOfA, null, resultOfB], instead of throwing an Error.

Promise.notAll = (list, options) => {
const resultPromises = list.map(value => {
return new Promise(async (resolve, reject) => {
try {
const result = await value
if ('resolve' in options) options.resolve(result)
resolve(result)
} catch(err) {
if ('reject' in options) options.reject(err)
resolve(null)
}
})
})
return Promise.all(resultPromises)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment