Skip to content

Instantly share code, notes, and snippets.

@brianarn
Created May 29, 2018 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianarn/e8c9aaa6ed8ba1e27cfcc21e014bf532 to your computer and use it in GitHub Desktop.
Save brianarn/e8c9aaa6ed8ba1e27cfcc21e014bf532 to your computer and use it in GitHub Desktop.
like `Promise.all` but for plain non-iterable objects
// Based on inspiration from some conversation in WeAllJS
// See wealljs.org for more info on the community!
// This is assuming a plain JS object which is why it's not using for-of, since
// plain objects aren't iterable
function objectPromiseAll(baseObject) {
return Promise.all(Object.values(baseObject)).then((resolvedValues) => {
const resolvedObject = {};
Object.keys(baseObject).forEach((key, index) => {
resolvedObject[key] = resolvedValues[index];
});
return resolvedObject;
});
}
// Using sample Promises from
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
// for a quick bit of testing
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
objectPromiseAll({ promise1, promise2, promise3 }).then((valuesObject) => {
console.log(valuesObject);
console.assert(valuesObject.promise1 === 3, 'Expected first value to be 3');
console.assert(valuesObject.promise2 === 42, 'Expected second value to be 42');
console.assert(valuesObject.promise3 === 'foo', 'Expected third value to be "foo"');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment