Skip to content

Instantly share code, notes, and snippets.

@yamadapc
Created March 17, 2014 19:52
Show Gist options
  • Save yamadapc/9606921 to your computer and use it in GitHub Desktop.
Save yamadapc/9606921 to your computer and use it in GitHub Desktop.
var Promise = require('bluebird');
_ = require('lodash');
/**
* Map an object, or a promise of an object, with the given `mapper` function
* with the signature `(value, key, obj)` where `value` is an object's `key`
* property's value.
*
* If the `mapper` function returns promises or thenables, the returned promise
* will wait for all the mapped results to be resolved as well.
*
* @param {Object|Promise e Object} obj
* @param {Function} fn
* @returns {Promise e Object} mapped_obj
*/
function mapValuesP(obj, fn) {
return Promise.cast(obj).then(function(obj) {
var keys = Object.keys(obj);
var valuesP = Promise.map(keys, function(key) {
return fn(obj[key], key, obj);
});
return valuesP.then(_.partial(_.zipObject, keys));
});
}
exports.mapValuesP = mapValuesP;
@yamadapc
Copy link
Author

should have support for a context object
(this is not the most efficient approach - it's more of a spec, than anything else)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment