Skip to content

Instantly share code, notes, and snippets.

@krusynth
Created November 1, 2019 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krusynth/90a70e4eb6c23d92201dc383219f417c to your computer and use it in GitHub Desktop.
Save krusynth/90a70e4eb6c23d92201dc383219f417c to your computer and use it in GitHub Desktop.
A wrapper for Promise.all that maps the return data into an object/hash.
'use strict';
/* Promises.all but uses an Object instead of an array.
*
* Usage:
*
* PromiseMap({
* 'a': new Promise((resolve, reject) => resolve(1)),
* 'b': new Promise((resolve, reject) => resolve(2))
* }).then(result => console.log('done', result));
*
* The resulting promise resolves to { a: 1, b: 2 }
*/
function PromiseMap(obj) {
let promises = [];
for(let key in obj) {
let promise = obj[key];
console.log('key', key);
promises.push(
promise.then(result => [key, result])
);
}
return Promise.all(promises).then(results => {
console.log('results', results);
let data = {};
results.forEach(result => data[result[0]] = result[1]);
return data;
});
}
module.exports = PromiseMap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment