Created
February 10, 2017 12:40
-
-
Save renaudtertrais/dffbd871ecf822ea9197edf08084c88c to your computer and use it in GitHub Desktop.
extend Promise.all() in order to accept plain object
This file contains hidden or 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
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