with.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2. /** @author Brian Cavalier */
  3. /** @author John Hann */
  4. (function(define) { 'use strict';
  5. define(function() {
  6. return function addWith(Promise) {
  7. /**
  8. * Returns a promise whose handlers will be called with `this` set to
  9. * the supplied receiver. Subsequent promises derived from the
  10. * returned promise will also have their handlers called with receiver
  11. * as `this`. Calling `with` with undefined or no arguments will return
  12. * a promise whose handlers will again be called in the usual Promises/A+
  13. * way (no `this`) thus safely undoing any previous `with` in the
  14. * promise chain.
  15. *
  16. * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
  17. * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
  18. *
  19. * @param {object} receiver `this` value for all handlers attached to
  20. * the returned promise.
  21. * @returns {Promise}
  22. */
  23. Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
  24. var p = this._beget();
  25. var child = p._handler;
  26. child.receiver = receiver;
  27. this._handler.chain(child, receiver);
  28. return p;
  29. };
  30. return Promise;
  31. };
  32. });
  33. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));