keys.js 2.0 KB

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