props.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. module.exports = function(
  3. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  4. var util = require("./util.js");
  5. var isObject = util.isObject;
  6. var es5 = require("./es5.js");
  7. function PropertiesPromiseArray(obj) {
  8. var keys = es5.keys(obj);
  9. var len = keys.length;
  10. var values = new Array(len * 2);
  11. for (var i = 0; i < len; ++i) {
  12. var key = keys[i];
  13. values[i] = obj[key];
  14. values[i + len] = key;
  15. }
  16. this.constructor$(values);
  17. }
  18. util.inherits(PropertiesPromiseArray, PromiseArray);
  19. PropertiesPromiseArray.prototype._init = function () {
  20. this._init$(undefined, -3) ;
  21. };
  22. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  23. this._values[index] = value;
  24. var totalResolved = ++this._totalResolved;
  25. if (totalResolved >= this._length) {
  26. var val = {};
  27. var keyOffset = this.length();
  28. for (var i = 0, len = this.length(); i < len; ++i) {
  29. val[this._values[i + keyOffset]] = this._values[i];
  30. }
  31. this._resolve(val);
  32. }
  33. };
  34. PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
  35. this._promise._progress({
  36. key: this._values[index + this.length()],
  37. value: value
  38. });
  39. };
  40. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  41. return false;
  42. };
  43. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  44. return len >> 1;
  45. };
  46. function props(promises) {
  47. var ret;
  48. var castValue = tryConvertToPromise(promises);
  49. if (!isObject(castValue)) {
  50. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
  51. } else if (castValue instanceof Promise) {
  52. ret = castValue._then(
  53. Promise.props, undefined, undefined, undefined, undefined);
  54. } else {
  55. ret = new PropertiesPromiseArray(castValue).promise();
  56. }
  57. if (castValue instanceof Promise) {
  58. ret._propagateFrom(castValue, 4);
  59. }
  60. return ret;
  61. }
  62. Promise.prototype.props = function () {
  63. return props(this);
  64. };
  65. Promise.props = function (promises) {
  66. return props(promises);
  67. };
  68. };