Last active
September 6, 2023 09:25
-
-
Save jameswragg/23b589b6b5eb4082ebb78a782c45a07b to your computer and use it in GitHub Desktop.
Promise.allSettled with Object keys
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
/** | |
* Resolves all Promises from a key/val object, returning the same structure but resolved | |
* @param {Object.<string, (function)>} obj - An object with any number of key-value pairs. | |
* @returns {{ values: object, rejected: object }} | |
*/ | |
const labelledPromises = async (obj) => { | |
const keys = Object.keys(obj); | |
const promises = Object.values(obj); | |
const results = await Promise.allSettled(promises); | |
const all = keys.reduce((acc, key, i) => { | |
acc[key] = results[i]; | |
return acc; | |
}, {}); | |
const rejected = Object.keys(all) | |
.filter((key) => all[key].status === 'rejected') | |
.reduce((acc, key) => { | |
acc[key] = all[key].reason; | |
return acc; | |
}, {}); | |
const values = Object.keys(all).reduce((acc, key) => { | |
acc[key] = all[key].value ?? undefined; | |
return acc; | |
}, {}); | |
return { | |
values, | |
rejected, | |
}; | |
}; | |
module.exports = labelledPromises; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given an object of labelled promises, get them back resolved with default support:
Will result in:
NOTE: you can use object destructuring to assign defaults, e.g.