bind.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
  3. var rejectThis = function(_, e) {
  4. this._reject(e);
  5. };
  6. var targetRejected = function(e, context) {
  7. context.promiseRejectionQueued = true;
  8. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  9. };
  10. var bindingResolved = function(thisArg, context) {
  11. this._setBoundTo(thisArg);
  12. if (this._isPending()) {
  13. this._resolveCallback(context.target);
  14. }
  15. };
  16. var bindingRejected = function(e, context) {
  17. if (!context.promiseRejectionQueued) this._reject(e);
  18. };
  19. Promise.prototype.bind = function (thisArg) {
  20. var maybePromise = tryConvertToPromise(thisArg);
  21. var ret = new Promise(INTERNAL);
  22. ret._propagateFrom(this, 1);
  23. var target = this._target();
  24. if (maybePromise instanceof Promise) {
  25. var context = {
  26. promiseRejectionQueued: false,
  27. promise: ret,
  28. target: target,
  29. bindingPromise: maybePromise
  30. };
  31. target._then(INTERNAL, targetRejected, ret._progress, ret, context);
  32. maybePromise._then(
  33. bindingResolved, bindingRejected, ret._progress, ret, context);
  34. } else {
  35. ret._setBoundTo(thisArg);
  36. ret._resolveCallback(target);
  37. }
  38. return ret;
  39. };
  40. Promise.prototype._setBoundTo = function (obj) {
  41. if (obj !== undefined) {
  42. this._bitField = this._bitField | 131072;
  43. this._boundTo = obj;
  44. } else {
  45. this._bitField = this._bitField & (~131072);
  46. }
  47. };
  48. Promise.prototype._isBound = function () {
  49. return (this._bitField & 131072) === 131072;
  50. };
  51. Promise.bind = function (thisArg, value) {
  52. var maybePromise = tryConvertToPromise(thisArg);
  53. var ret = new Promise(INTERNAL);
  54. if (maybePromise instanceof Promise) {
  55. maybePromise._then(function(thisArg) {
  56. ret._setBoundTo(thisArg);
  57. ret._resolveCallback(value);
  58. }, ret._reject, ret._progress, ret, null);
  59. } else {
  60. ret._setBoundTo(thisArg);
  61. ret._resolveCallback(value);
  62. }
  63. return ret;
  64. };
  65. };