UNPKG

2.02 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2011-2013 original author or authors */
2
3/**
4 * Licensed under the MIT License at:
5 * http://www.opensource.org/licenses/mit-license.php
6 *
7 * @author Brian Cavalier
8 * @author John Hann
9 */
10(function(define) { 'use strict';
11define(function(require) {
12
13 var when = require('./when');
14 var Promise = when.Promise;
15 var toPromise = when.resolve;
16
17 return {
18 all: when.lift(all),
19 map: map
20 };
21
22 /**
23 * Resolve all the key-value pairs in the supplied object or promise
24 * for an object.
25 * @param {Promise|object} object or promise for object whose key-value pairs
26 * will be resolved
27 * @returns {Promise} promise for an object with the fully resolved key-value pairs
28 */
29 function all(object) {
30 var p = Promise._defer();
31 var resolver = Promise._handler(p);
32
33 var results = {};
34 var keys = Object.keys(object);
35 var pending = keys.length;
36
37 for(var i=0, k; i<keys.length; ++i) {
38 k = keys[i];
39 Promise._handler(object[k]).fold(settleKey, k, results, resolver);
40 }
41
42 if(pending === 0) {
43 resolver.resolve(results);
44 }
45
46 return p;
47
48 function settleKey(k, x, resolver) {
49 /*jshint validthis:true*/
50 this[k] = x;
51 if(--pending === 0) {
52 resolver.resolve(results);
53 }
54 }
55 }
56
57 /**
58 * Map values in the supplied object's keys
59 * @param {Promise|object} object or promise for object whose key-value pairs
60 * will be reduced
61 * @param {function(value:*, key:String):*} f mapping function which may
62 * return either a promise or a value
63 * @returns {Promise} promise for an object with the mapped and fully
64 * resolved key-value pairs
65 */
66 function map(object, f) {
67 return toPromise(object).then(function(object) {
68 return all(Object.keys(object).reduce(function(o, k) {
69 o[k] = toPromise(object[k]).fold(mapWithKey, k);
70 return o;
71 }, {}));
72 });
73
74 function mapWithKey(k, x) {
75 return f(x, k);
76 }
77 }
78
79});
80})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });