Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Created February 10, 2017 12:40
Show Gist options
  • Save renaudtertrais/dffbd871ecf822ea9197edf08084c88c to your computer and use it in GitHub Desktop.
Save renaudtertrais/dffbd871ecf822ea9197edf08084c88c to your computer and use it in GitHub Desktop.
extend Promise.all() in order to accept plain object
const assign = (obj, key, value) => Object.assign({}, obj, { [key]: value });
const promiseAllObject = obj => {
const keys = Object.keys(obj);
return Promise.all(Object.values(obj))
.then(results => results.map((val, i) => [keys[i], val]))
.then(results => results.reduce((res, val) => assign(res, ...val), {}));
}
// Example:
const delay = (cb, time) => new Promise((res) => setTimeout(() => res(cb()), time));
const promises = {
foo: delay(() => 'foo', 1000),
bar: delay(() => 'bar', 2000),
};
promiseAllObject(promises).then(console.log)
/* 2s after...
{
bar: "bar",
foo: "foo"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment