I love JavaScript Promises and all the cool things you can do with them. The other day I found a need to construct a comlex object using results of a bunch of promises. My first thought was to just use Promise.all
and be over with it, but I figured there must be a better way.
Lo and behold, I found promise-from-hash by Michael which be is basically like Promise.all
but for objects, instead of arrays. It’s a very convenient tool to have when you need it.
npm install promise-from-hash
Usage
Here’s a simple example of populating an object with results of a couple of API calls. Same pattern could be applied to loading multiple files, or multiple database requests and so on. Very handy and simple.
var Promise = require('bluebird');
var promiseFromHash = require('promise-from-hash');
var request = require('request');
function fetch(city) {
return new Promise(function(resolve) {
request.get('http://api.openweathermap.org/data/2.5/weather', {json: true, qs: {q: city}}, function(err, response) {
resolve(response.body);
});
});
}
var weather = {
'sf': fetch('San Francisco'),
'nyc': fetch('New York')
};
promiseFromHash(weather).then(function(weather) {
console.log(JSON.stringify(weather, null, 2));
});
What Else?
Checkout the runnable example and github example repository. Do you use any non-standard Promise tools? Whould love to hear about it.