Skip to content

Instantly share code, notes, and snippets.

@saadtazi
Last active July 20, 2023 12:02
Show Gist options
  • Save saadtazi/144ceb51f930958e1b2a to your computer and use it in GitHub Desktop.
Save saadtazi/144ceb51f930958e1b2a to your computer and use it in GitHub Desktop.
buebird inspired Promise.props using native Promise.all()
Promise.props = function (props) {
return Promise.all(Object.keys(props).map(function (key) {
// ok with val, func, prom?
return Promise.resolve(props[key]).then(function (res) {
var one = {};
one[key] = res;
return one;
});
}))
.then(function (arr) {
return arr.reduce(function (memo, oneRes) {
var key = Object.keys(oneRes)[0];
memo[key] = oneRes[key];
return memo;
}, {});
});
};

Usage

Promise.props({ a: 1, b: Promise.resolve(14) }).then(function (a) {
    console.log('resolved:::', a);
});
/// resolved::: { a: 1, b: 14 }

Promise.props({ a: 1, b: Promise.reject(14) }).catch(function (err) {
    console.log('rejected:::', err);
});
/// rejected::: 14
@Alexsey
Copy link

Alexsey commented Feb 13, 2018

With modern ES is could be just

Promise.props = async obj =>
  Object.assign({}, ...(await Promise.all(
    Object.entries(obj).map(async ([key, value]) => ({[key]: await value}))
  )))

@sekoyo
Copy link

sekoyo commented Jul 20, 2023

With modern ES is could be just

Promise.props = async obj =>
  Object.assign({}, ...(await Promise.all(
    Object.entries(obj).map(async ([key, value]) => ({[key]: await value}))
  )))

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment