Created
November 1, 2019 21:16
-
-
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.
This file contains 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
'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