Promise.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.Promise=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  3. /** @author Brian Cavalier */
  4. /** @author John Hann */
  5. /**
  6. * ES6 global Promise shim
  7. */
  8. var unhandledRejections = require('../lib/decorators/unhandledRejection');
  9. var PromiseConstructor = unhandledRejections(require('../lib/Promise'));
  10. module.exports = typeof global != 'undefined' ? (global.Promise = PromiseConstructor)
  11. : typeof self != 'undefined' ? (self.Promise = PromiseConstructor)
  12. : PromiseConstructor;
  13. },{"../lib/Promise":2,"../lib/decorators/unhandledRejection":4}],2:[function(require,module,exports){
  14. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  15. /** @author Brian Cavalier */
  16. /** @author John Hann */
  17. (function(define) { 'use strict';
  18. define(function (require) {
  19. var makePromise = require('./makePromise');
  20. var Scheduler = require('./Scheduler');
  21. var async = require('./env').asap;
  22. return makePromise({
  23. scheduler: new Scheduler(async)
  24. });
  25. });
  26. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  27. },{"./Scheduler":3,"./env":5,"./makePromise":7}],3:[function(require,module,exports){
  28. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  29. /** @author Brian Cavalier */
  30. /** @author John Hann */
  31. (function(define) { 'use strict';
  32. define(function() {
  33. // Credit to Twisol (https://github.com/Twisol) for suggesting
  34. // this type of extensible queue + trampoline approach for next-tick conflation.
  35. /**
  36. * Async task scheduler
  37. * @param {function} async function to schedule a single async function
  38. * @constructor
  39. */
  40. function Scheduler(async) {
  41. this._async = async;
  42. this._running = false;
  43. this._queue = new Array(1<<16);
  44. this._queueLen = 0;
  45. this._afterQueue = new Array(1<<4);
  46. this._afterQueueLen = 0;
  47. var self = this;
  48. this.drain = function() {
  49. self._drain();
  50. };
  51. }
  52. /**
  53. * Enqueue a task
  54. * @param {{ run:function }} task
  55. */
  56. Scheduler.prototype.enqueue = function(task) {
  57. this._queue[this._queueLen++] = task;
  58. this.run();
  59. };
  60. /**
  61. * Enqueue a task to run after the main task queue
  62. * @param {{ run:function }} task
  63. */
  64. Scheduler.prototype.afterQueue = function(task) {
  65. this._afterQueue[this._afterQueueLen++] = task;
  66. this.run();
  67. };
  68. Scheduler.prototype.run = function() {
  69. if (!this._running) {
  70. this._running = true;
  71. this._async(this.drain);
  72. }
  73. };
  74. /**
  75. * Drain the handler queue entirely, and then the after queue
  76. */
  77. Scheduler.prototype._drain = function() {
  78. var i = 0;
  79. for (; i < this._queueLen; ++i) {
  80. this._queue[i].run();
  81. this._queue[i] = void 0;
  82. }
  83. this._queueLen = 0;
  84. this._running = false;
  85. for (i = 0; i < this._afterQueueLen; ++i) {
  86. this._afterQueue[i].run();
  87. this._afterQueue[i] = void 0;
  88. }
  89. this._afterQueueLen = 0;
  90. };
  91. return Scheduler;
  92. });
  93. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  94. },{}],4:[function(require,module,exports){
  95. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  96. /** @author Brian Cavalier */
  97. /** @author John Hann */
  98. (function(define) { 'use strict';
  99. define(function(require) {
  100. var setTimer = require('../env').setTimer;
  101. var format = require('../format');
  102. return function unhandledRejection(Promise) {
  103. var logError = noop;
  104. var logInfo = noop;
  105. var localConsole;
  106. if(typeof console !== 'undefined') {
  107. // Alias console to prevent things like uglify's drop_console option from
  108. // removing console.log/error. Unhandled rejections fall into the same
  109. // category as uncaught exceptions, and build tools shouldn't silence them.
  110. localConsole = console;
  111. logError = typeof localConsole.error !== 'undefined'
  112. ? function (e) { localConsole.error(e); }
  113. : function (e) { localConsole.log(e); };
  114. logInfo = typeof localConsole.info !== 'undefined'
  115. ? function (e) { localConsole.info(e); }
  116. : function (e) { localConsole.log(e); };
  117. }
  118. Promise.onPotentiallyUnhandledRejection = function(rejection) {
  119. enqueue(report, rejection);
  120. };
  121. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  122. enqueue(unreport, rejection);
  123. };
  124. Promise.onFatalRejection = function(rejection) {
  125. enqueue(throwit, rejection.value);
  126. };
  127. var tasks = [];
  128. var reported = [];
  129. var running = null;
  130. function report(r) {
  131. if(!r.handled) {
  132. reported.push(r);
  133. logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
  134. }
  135. }
  136. function unreport(r) {
  137. var i = reported.indexOf(r);
  138. if(i >= 0) {
  139. reported.splice(i, 1);
  140. logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
  141. }
  142. }
  143. function enqueue(f, x) {
  144. tasks.push(f, x);
  145. if(running === null) {
  146. running = setTimer(flush, 0);
  147. }
  148. }
  149. function flush() {
  150. running = null;
  151. while(tasks.length > 0) {
  152. tasks.shift()(tasks.shift());
  153. }
  154. }
  155. return Promise;
  156. };
  157. function throwit(e) {
  158. throw e;
  159. }
  160. function noop() {}
  161. });
  162. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  163. },{"../env":5,"../format":6}],5:[function(require,module,exports){
  164. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  165. /** @author Brian Cavalier */
  166. /** @author John Hann */
  167. /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
  168. (function(define) { 'use strict';
  169. define(function(require) {
  170. /*jshint maxcomplexity:6*/
  171. // Sniff "best" async scheduling option
  172. // Prefer process.nextTick or MutationObserver, then check for
  173. // setTimeout, and finally vertx, since its the only env that doesn't
  174. // have setTimeout
  175. var MutationObs;
  176. var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
  177. // Default env
  178. var setTimer = function(f, ms) { return setTimeout(f, ms); };
  179. var clearTimer = function(t) { return clearTimeout(t); };
  180. var asap = function (f) { return capturedSetTimeout(f, 0); };
  181. // Detect specific env
  182. if (isNode()) { // Node
  183. asap = function (f) { return process.nextTick(f); };
  184. } else if (MutationObs = hasMutationObserver()) { // Modern browser
  185. asap = initMutationObserver(MutationObs);
  186. } else if (!capturedSetTimeout) { // vert.x
  187. var vertxRequire = require;
  188. var vertx = vertxRequire('vertx');
  189. setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
  190. clearTimer = vertx.cancelTimer;
  191. asap = vertx.runOnLoop || vertx.runOnContext;
  192. }
  193. return {
  194. setTimer: setTimer,
  195. clearTimer: clearTimer,
  196. asap: asap
  197. };
  198. function isNode () {
  199. return typeof process !== 'undefined' && process !== null &&
  200. typeof process.nextTick === 'function';
  201. }
  202. function hasMutationObserver () {
  203. return (typeof MutationObserver === 'function' && MutationObserver) ||
  204. (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
  205. }
  206. function initMutationObserver(MutationObserver) {
  207. var scheduled;
  208. var node = document.createTextNode('');
  209. var o = new MutationObserver(run);
  210. o.observe(node, { characterData: true });
  211. function run() {
  212. var f = scheduled;
  213. scheduled = void 0;
  214. f();
  215. }
  216. var i = 0;
  217. return function (f) {
  218. scheduled = f;
  219. node.data = (i ^= 1);
  220. };
  221. }
  222. });
  223. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  224. },{}],6:[function(require,module,exports){
  225. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  226. /** @author Brian Cavalier */
  227. /** @author John Hann */
  228. (function(define) { 'use strict';
  229. define(function() {
  230. return {
  231. formatError: formatError,
  232. formatObject: formatObject,
  233. tryStringify: tryStringify
  234. };
  235. /**
  236. * Format an error into a string. If e is an Error and has a stack property,
  237. * it's returned. Otherwise, e is formatted using formatObject, with a
  238. * warning added about e not being a proper Error.
  239. * @param {*} e
  240. * @returns {String} formatted string, suitable for output to developers
  241. */
  242. function formatError(e) {
  243. var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e);
  244. return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
  245. }
  246. /**
  247. * Format an object, detecting "plain" objects and running them through
  248. * JSON.stringify if possible.
  249. * @param {Object} o
  250. * @returns {string}
  251. */
  252. function formatObject(o) {
  253. var s = String(o);
  254. if(s === '[object Object]' && typeof JSON !== 'undefined') {
  255. s = tryStringify(o, s);
  256. }
  257. return s;
  258. }
  259. /**
  260. * Try to return the result of JSON.stringify(x). If that fails, return
  261. * defaultValue
  262. * @param {*} x
  263. * @param {*} defaultValue
  264. * @returns {String|*} JSON.stringify(x) or defaultValue
  265. */
  266. function tryStringify(x, defaultValue) {
  267. try {
  268. return JSON.stringify(x);
  269. } catch(e) {
  270. return defaultValue;
  271. }
  272. }
  273. });
  274. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  275. },{}],7:[function(require,module,exports){
  276. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  277. /** @author Brian Cavalier */
  278. /** @author John Hann */
  279. (function(define) { 'use strict';
  280. define(function() {
  281. return function makePromise(environment) {
  282. var tasks = environment.scheduler;
  283. var objectCreate = Object.create ||
  284. function(proto) {
  285. function Child() {}
  286. Child.prototype = proto;
  287. return new Child();
  288. };
  289. /**
  290. * Create a promise whose fate is determined by resolver
  291. * @constructor
  292. * @returns {Promise} promise
  293. * @name Promise
  294. */
  295. function Promise(resolver, handler) {
  296. this._handler = resolver === Handler ? handler : init(resolver);
  297. }
  298. /**
  299. * Run the supplied resolver
  300. * @param resolver
  301. * @returns {Pending}
  302. */
  303. function init(resolver) {
  304. var handler = new Pending();
  305. try {
  306. resolver(promiseResolve, promiseReject, promiseNotify);
  307. } catch (e) {
  308. promiseReject(e);
  309. }
  310. return handler;
  311. /**
  312. * Transition from pre-resolution state to post-resolution state, notifying
  313. * all listeners of the ultimate fulfillment or rejection
  314. * @param {*} x resolution value
  315. */
  316. function promiseResolve (x) {
  317. handler.resolve(x);
  318. }
  319. /**
  320. * Reject this promise with reason, which will be used verbatim
  321. * @param {Error|*} reason rejection reason, strongly suggested
  322. * to be an Error type
  323. */
  324. function promiseReject (reason) {
  325. handler.reject(reason);
  326. }
  327. /**
  328. * @deprecated
  329. * Issue a progress event, notifying all progress listeners
  330. * @param {*} x progress event payload to pass to all listeners
  331. */
  332. function promiseNotify (x) {
  333. handler.notify(x);
  334. }
  335. }
  336. // Creation
  337. Promise.resolve = resolve;
  338. Promise.reject = reject;
  339. Promise.never = never;
  340. Promise._defer = defer;
  341. Promise._handler = getHandler;
  342. /**
  343. * Returns a trusted promise. If x is already a trusted promise, it is
  344. * returned, otherwise returns a new trusted Promise which follows x.
  345. * @param {*} x
  346. * @return {Promise} promise
  347. */
  348. function resolve(x) {
  349. return isPromise(x) ? x
  350. : new Promise(Handler, new Async(getHandler(x)));
  351. }
  352. /**
  353. * Return a reject promise with x as its reason (x is used verbatim)
  354. * @param {*} x
  355. * @returns {Promise} rejected promise
  356. */
  357. function reject(x) {
  358. return new Promise(Handler, new Async(new Rejected(x)));
  359. }
  360. /**
  361. * Return a promise that remains pending forever
  362. * @returns {Promise} forever-pending promise.
  363. */
  364. function never() {
  365. return foreverPendingPromise; // Should be frozen
  366. }
  367. /**
  368. * Creates an internal {promise, resolver} pair
  369. * @private
  370. * @returns {Promise}
  371. */
  372. function defer() {
  373. return new Promise(Handler, new Pending());
  374. }
  375. // Transformation and flow control
  376. /**
  377. * Transform this promise's fulfillment value, returning a new Promise
  378. * for the transformed result. If the promise cannot be fulfilled, onRejected
  379. * is called with the reason. onProgress *may* be called with updates toward
  380. * this promise's fulfillment.
  381. * @param {function=} onFulfilled fulfillment handler
  382. * @param {function=} onRejected rejection handler
  383. * @param {function=} onProgress @deprecated progress handler
  384. * @return {Promise} new promise
  385. */
  386. Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
  387. var parent = this._handler;
  388. var state = parent.join().state();
  389. if ((typeof onFulfilled !== 'function' && state > 0) ||
  390. (typeof onRejected !== 'function' && state < 0)) {
  391. // Short circuit: value will not change, simply share handler
  392. return new this.constructor(Handler, parent);
  393. }
  394. var p = this._beget();
  395. var child = p._handler;
  396. parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
  397. return p;
  398. };
  399. /**
  400. * If this promise cannot be fulfilled due to an error, call onRejected to
  401. * handle the error. Shortcut for .then(undefined, onRejected)
  402. * @param {function?} onRejected
  403. * @return {Promise}
  404. */
  405. Promise.prototype['catch'] = function(onRejected) {
  406. return this.then(void 0, onRejected);
  407. };
  408. /**
  409. * Creates a new, pending promise of the same type as this promise
  410. * @private
  411. * @returns {Promise}
  412. */
  413. Promise.prototype._beget = function() {
  414. return begetFrom(this._handler, this.constructor);
  415. };
  416. function begetFrom(parent, Promise) {
  417. var child = new Pending(parent.receiver, parent.join().context);
  418. return new Promise(Handler, child);
  419. }
  420. // Array combinators
  421. Promise.all = all;
  422. Promise.race = race;
  423. Promise._traverse = traverse;
  424. /**
  425. * Return a promise that will fulfill when all promises in the
  426. * input array have fulfilled, or will reject when one of the
  427. * promises rejects.
  428. * @param {array} promises array of promises
  429. * @returns {Promise} promise for array of fulfillment values
  430. */
  431. function all(promises) {
  432. return traverseWith(snd, null, promises);
  433. }
  434. /**
  435. * Array<Promise<X>> -> Promise<Array<f(X)>>
  436. * @private
  437. * @param {function} f function to apply to each promise's value
  438. * @param {Array} promises array of promises
  439. * @returns {Promise} promise for transformed values
  440. */
  441. function traverse(f, promises) {
  442. return traverseWith(tryCatch2, f, promises);
  443. }
  444. function traverseWith(tryMap, f, promises) {
  445. var handler = typeof f === 'function' ? mapAt : settleAt;
  446. var resolver = new Pending();
  447. var pending = promises.length >>> 0;
  448. var results = new Array(pending);
  449. for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
  450. x = promises[i];
  451. if (x === void 0 && !(i in promises)) {
  452. --pending;
  453. continue;
  454. }
  455. traverseAt(promises, handler, i, x, resolver);
  456. }
  457. if(pending === 0) {
  458. resolver.become(new Fulfilled(results));
  459. }
  460. return new Promise(Handler, resolver);
  461. function mapAt(i, x, resolver) {
  462. if(!resolver.resolved) {
  463. traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
  464. }
  465. }
  466. function settleAt(i, x, resolver) {
  467. results[i] = x;
  468. if(--pending === 0) {
  469. resolver.become(new Fulfilled(results));
  470. }
  471. }
  472. }
  473. function traverseAt(promises, handler, i, x, resolver) {
  474. if (maybeThenable(x)) {
  475. var h = getHandlerMaybeThenable(x);
  476. var s = h.state();
  477. if (s === 0) {
  478. h.fold(handler, i, void 0, resolver);
  479. } else if (s > 0) {
  480. handler(i, h.value, resolver);
  481. } else {
  482. resolver.become(h);
  483. visitRemaining(promises, i+1, h);
  484. }
  485. } else {
  486. handler(i, x, resolver);
  487. }
  488. }
  489. Promise._visitRemaining = visitRemaining;
  490. function visitRemaining(promises, start, handler) {
  491. for(var i=start; i<promises.length; ++i) {
  492. markAsHandled(getHandler(promises[i]), handler);
  493. }
  494. }
  495. function markAsHandled(h, handler) {
  496. if(h === handler) {
  497. return;
  498. }
  499. var s = h.state();
  500. if(s === 0) {
  501. h.visit(h, void 0, h._unreport);
  502. } else if(s < 0) {
  503. h._unreport();
  504. }
  505. }
  506. /**
  507. * Fulfill-reject competitive race. Return a promise that will settle
  508. * to the same state as the earliest input promise to settle.
  509. *
  510. * WARNING: The ES6 Promise spec requires that race()ing an empty array
  511. * must return a promise that is pending forever. This implementation
  512. * returns a singleton forever-pending promise, the same singleton that is
  513. * returned by Promise.never(), thus can be checked with ===
  514. *
  515. * @param {array} promises array of promises to race
  516. * @returns {Promise} if input is non-empty, a promise that will settle
  517. * to the same outcome as the earliest input promise to settle. if empty
  518. * is empty, returns a promise that will never settle.
  519. */
  520. function race(promises) {
  521. if(typeof promises !== 'object' || promises === null) {
  522. return reject(new TypeError('non-iterable passed to race()'));
  523. }
  524. // Sigh, race([]) is untestable unless we return *something*
  525. // that is recognizable without calling .then() on it.
  526. return promises.length === 0 ? never()
  527. : promises.length === 1 ? resolve(promises[0])
  528. : runRace(promises);
  529. }
  530. function runRace(promises) {
  531. var resolver = new Pending();
  532. var i, x, h;
  533. for(i=0; i<promises.length; ++i) {
  534. x = promises[i];
  535. if (x === void 0 && !(i in promises)) {
  536. continue;
  537. }
  538. h = getHandler(x);
  539. if(h.state() !== 0) {
  540. resolver.become(h);
  541. visitRemaining(promises, i+1, h);
  542. break;
  543. } else {
  544. h.visit(resolver, resolver.resolve, resolver.reject);
  545. }
  546. }
  547. return new Promise(Handler, resolver);
  548. }
  549. // Promise internals
  550. // Below this, everything is @private
  551. /**
  552. * Get an appropriate handler for x, without checking for cycles
  553. * @param {*} x
  554. * @returns {object} handler
  555. */
  556. function getHandler(x) {
  557. if(isPromise(x)) {
  558. return x._handler.join();
  559. }
  560. return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
  561. }
  562. /**
  563. * Get a handler for thenable x.
  564. * NOTE: You must only call this if maybeThenable(x) == true
  565. * @param {object|function|Promise} x
  566. * @returns {object} handler
  567. */
  568. function getHandlerMaybeThenable(x) {
  569. return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
  570. }
  571. /**
  572. * Get a handler for potentially untrusted thenable x
  573. * @param {*} x
  574. * @returns {object} handler
  575. */
  576. function getHandlerUntrusted(x) {
  577. try {
  578. var untrustedThen = x.then;
  579. return typeof untrustedThen === 'function'
  580. ? new Thenable(untrustedThen, x)
  581. : new Fulfilled(x);
  582. } catch(e) {
  583. return new Rejected(e);
  584. }
  585. }
  586. /**
  587. * Handler for a promise that is pending forever
  588. * @constructor
  589. */
  590. function Handler() {}
  591. Handler.prototype.when
  592. = Handler.prototype.become
  593. = Handler.prototype.notify // deprecated
  594. = Handler.prototype.fail
  595. = Handler.prototype._unreport
  596. = Handler.prototype._report
  597. = noop;
  598. Handler.prototype._state = 0;
  599. Handler.prototype.state = function() {
  600. return this._state;
  601. };
  602. /**
  603. * Recursively collapse handler chain to find the handler
  604. * nearest to the fully resolved value.
  605. * @returns {object} handler nearest the fully resolved value
  606. */
  607. Handler.prototype.join = function() {
  608. var h = this;
  609. while(h.handler !== void 0) {
  610. h = h.handler;
  611. }
  612. return h;
  613. };
  614. Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
  615. this.when({
  616. resolver: to,
  617. receiver: receiver,
  618. fulfilled: fulfilled,
  619. rejected: rejected,
  620. progress: progress
  621. });
  622. };
  623. Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
  624. this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
  625. };
  626. Handler.prototype.fold = function(f, z, c, to) {
  627. this.when(new Fold(f, z, c, to));
  628. };
  629. /**
  630. * Handler that invokes fail() on any handler it becomes
  631. * @constructor
  632. */
  633. function FailIfRejected() {}
  634. inherit(Handler, FailIfRejected);
  635. FailIfRejected.prototype.become = function(h) {
  636. h.fail();
  637. };
  638. var failIfRejected = new FailIfRejected();
  639. /**
  640. * Handler that manages a queue of consumers waiting on a pending promise
  641. * @constructor
  642. */
  643. function Pending(receiver, inheritedContext) {
  644. Promise.createContext(this, inheritedContext);
  645. this.consumers = void 0;
  646. this.receiver = receiver;
  647. this.handler = void 0;
  648. this.resolved = false;
  649. }
  650. inherit(Handler, Pending);
  651. Pending.prototype._state = 0;
  652. Pending.prototype.resolve = function(x) {
  653. this.become(getHandler(x));
  654. };
  655. Pending.prototype.reject = function(x) {
  656. if(this.resolved) {
  657. return;
  658. }
  659. this.become(new Rejected(x));
  660. };
  661. Pending.prototype.join = function() {
  662. if (!this.resolved) {
  663. return this;
  664. }
  665. var h = this;
  666. while (h.handler !== void 0) {
  667. h = h.handler;
  668. if (h === this) {
  669. return this.handler = cycle();
  670. }
  671. }
  672. return h;
  673. };
  674. Pending.prototype.run = function() {
  675. var q = this.consumers;
  676. var handler = this.join();
  677. this.consumers = void 0;
  678. for (var i = 0; i < q.length; ++i) {
  679. handler.when(q[i]);
  680. }
  681. };
  682. Pending.prototype.become = function(handler) {
  683. if(this.resolved) {
  684. return;
  685. }
  686. this.resolved = true;
  687. this.handler = handler;
  688. if(this.consumers !== void 0) {
  689. tasks.enqueue(this);
  690. }
  691. if(this.context !== void 0) {
  692. handler._report(this.context);
  693. }
  694. };
  695. Pending.prototype.when = function(continuation) {
  696. if(this.resolved) {
  697. tasks.enqueue(new ContinuationTask(continuation, this.handler));
  698. } else {
  699. if(this.consumers === void 0) {
  700. this.consumers = [continuation];
  701. } else {
  702. this.consumers.push(continuation);
  703. }
  704. }
  705. };
  706. /**
  707. * @deprecated
  708. */
  709. Pending.prototype.notify = function(x) {
  710. if(!this.resolved) {
  711. tasks.enqueue(new ProgressTask(x, this));
  712. }
  713. };
  714. Pending.prototype.fail = function(context) {
  715. var c = typeof context === 'undefined' ? this.context : context;
  716. this.resolved && this.handler.join().fail(c);
  717. };
  718. Pending.prototype._report = function(context) {
  719. this.resolved && this.handler.join()._report(context);
  720. };
  721. Pending.prototype._unreport = function() {
  722. this.resolved && this.handler.join()._unreport();
  723. };
  724. /**
  725. * Wrap another handler and force it into a future stack
  726. * @param {object} handler
  727. * @constructor
  728. */
  729. function Async(handler) {
  730. this.handler = handler;
  731. }
  732. inherit(Handler, Async);
  733. Async.prototype.when = function(continuation) {
  734. tasks.enqueue(new ContinuationTask(continuation, this));
  735. };
  736. Async.prototype._report = function(context) {
  737. this.join()._report(context);
  738. };
  739. Async.prototype._unreport = function() {
  740. this.join()._unreport();
  741. };
  742. /**
  743. * Handler that wraps an untrusted thenable and assimilates it in a future stack
  744. * @param {function} then
  745. * @param {{then: function}} thenable
  746. * @constructor
  747. */
  748. function Thenable(then, thenable) {
  749. Pending.call(this);
  750. tasks.enqueue(new AssimilateTask(then, thenable, this));
  751. }
  752. inherit(Pending, Thenable);
  753. /**
  754. * Handler for a fulfilled promise
  755. * @param {*} x fulfillment value
  756. * @constructor
  757. */
  758. function Fulfilled(x) {
  759. Promise.createContext(this);
  760. this.value = x;
  761. }
  762. inherit(Handler, Fulfilled);
  763. Fulfilled.prototype._state = 1;
  764. Fulfilled.prototype.fold = function(f, z, c, to) {
  765. runContinuation3(f, z, this, c, to);
  766. };
  767. Fulfilled.prototype.when = function(cont) {
  768. runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
  769. };
  770. var errorId = 0;
  771. /**
  772. * Handler for a rejected promise
  773. * @param {*} x rejection reason
  774. * @constructor
  775. */
  776. function Rejected(x) {
  777. Promise.createContext(this);
  778. this.id = ++errorId;
  779. this.value = x;
  780. this.handled = false;
  781. this.reported = false;
  782. this._report();
  783. }
  784. inherit(Handler, Rejected);
  785. Rejected.prototype._state = -1;
  786. Rejected.prototype.fold = function(f, z, c, to) {
  787. to.become(this);
  788. };
  789. Rejected.prototype.when = function(cont) {
  790. if(typeof cont.rejected === 'function') {
  791. this._unreport();
  792. }
  793. runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
  794. };
  795. Rejected.prototype._report = function(context) {
  796. tasks.afterQueue(new ReportTask(this, context));
  797. };
  798. Rejected.prototype._unreport = function() {
  799. if(this.handled) {
  800. return;
  801. }
  802. this.handled = true;
  803. tasks.afterQueue(new UnreportTask(this));
  804. };
  805. Rejected.prototype.fail = function(context) {
  806. Promise.onFatalRejection(this, context === void 0 ? this.context : context);
  807. };
  808. function ReportTask(rejection, context) {
  809. this.rejection = rejection;
  810. this.context = context;
  811. }
  812. ReportTask.prototype.run = function() {
  813. if(!this.rejection.handled) {
  814. this.rejection.reported = true;
  815. Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
  816. }
  817. };
  818. function UnreportTask(rejection) {
  819. this.rejection = rejection;
  820. }
  821. UnreportTask.prototype.run = function() {
  822. if(this.rejection.reported) {
  823. Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
  824. }
  825. };
  826. // Unhandled rejection hooks
  827. // By default, everything is a noop
  828. // TODO: Better names: "annotate"?
  829. Promise.createContext
  830. = Promise.enterContext
  831. = Promise.exitContext
  832. = Promise.onPotentiallyUnhandledRejection
  833. = Promise.onPotentiallyUnhandledRejectionHandled
  834. = Promise.onFatalRejection
  835. = noop;
  836. // Errors and singletons
  837. var foreverPendingHandler = new Handler();
  838. var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
  839. function cycle() {
  840. return new Rejected(new TypeError('Promise cycle'));
  841. }
  842. // Task runners
  843. /**
  844. * Run a single consumer
  845. * @constructor
  846. */
  847. function ContinuationTask(continuation, handler) {
  848. this.continuation = continuation;
  849. this.handler = handler;
  850. }
  851. ContinuationTask.prototype.run = function() {
  852. this.handler.join().when(this.continuation);
  853. };
  854. /**
  855. * Run a queue of progress handlers
  856. * @constructor
  857. */
  858. function ProgressTask(value, handler) {
  859. this.handler = handler;
  860. this.value = value;
  861. }
  862. ProgressTask.prototype.run = function() {
  863. var q = this.handler.consumers;
  864. if(q === void 0) {
  865. return;
  866. }
  867. for (var c, i = 0; i < q.length; ++i) {
  868. c = q[i];
  869. runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
  870. }
  871. };
  872. /**
  873. * Assimilate a thenable, sending it's value to resolver
  874. * @param {function} then
  875. * @param {object|function} thenable
  876. * @param {object} resolver
  877. * @constructor
  878. */
  879. function AssimilateTask(then, thenable, resolver) {
  880. this._then = then;
  881. this.thenable = thenable;
  882. this.resolver = resolver;
  883. }
  884. AssimilateTask.prototype.run = function() {
  885. var h = this.resolver;
  886. tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
  887. function _resolve(x) { h.resolve(x); }
  888. function _reject(x) { h.reject(x); }
  889. function _notify(x) { h.notify(x); }
  890. };
  891. function tryAssimilate(then, thenable, resolve, reject, notify) {
  892. try {
  893. then.call(thenable, resolve, reject, notify);
  894. } catch (e) {
  895. reject(e);
  896. }
  897. }
  898. /**
  899. * Fold a handler value with z
  900. * @constructor
  901. */
  902. function Fold(f, z, c, to) {
  903. this.f = f; this.z = z; this.c = c; this.to = to;
  904. this.resolver = failIfRejected;
  905. this.receiver = this;
  906. }
  907. Fold.prototype.fulfilled = function(x) {
  908. this.f.call(this.c, this.z, x, this.to);
  909. };
  910. Fold.prototype.rejected = function(x) {
  911. this.to.reject(x);
  912. };
  913. Fold.prototype.progress = function(x) {
  914. this.to.notify(x);
  915. };
  916. // Other helpers
  917. /**
  918. * @param {*} x
  919. * @returns {boolean} true iff x is a trusted Promise
  920. */
  921. function isPromise(x) {
  922. return x instanceof Promise;
  923. }
  924. /**
  925. * Test just enough to rule out primitives, in order to take faster
  926. * paths in some code
  927. * @param {*} x
  928. * @returns {boolean} false iff x is guaranteed *not* to be a thenable
  929. */
  930. function maybeThenable(x) {
  931. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  932. }
  933. function runContinuation1(f, h, receiver, next) {
  934. if(typeof f !== 'function') {
  935. return next.become(h);
  936. }
  937. Promise.enterContext(h);
  938. tryCatchReject(f, h.value, receiver, next);
  939. Promise.exitContext();
  940. }
  941. function runContinuation3(f, x, h, receiver, next) {
  942. if(typeof f !== 'function') {
  943. return next.become(h);
  944. }
  945. Promise.enterContext(h);
  946. tryCatchReject3(f, x, h.value, receiver, next);
  947. Promise.exitContext();
  948. }
  949. /**
  950. * @deprecated
  951. */
  952. function runNotify(f, x, h, receiver, next) {
  953. if(typeof f !== 'function') {
  954. return next.notify(x);
  955. }
  956. Promise.enterContext(h);
  957. tryCatchReturn(f, x, receiver, next);
  958. Promise.exitContext();
  959. }
  960. function tryCatch2(f, a, b) {
  961. try {
  962. return f(a, b);
  963. } catch(e) {
  964. return reject(e);
  965. }
  966. }
  967. /**
  968. * Return f.call(thisArg, x), or if it throws return a rejected promise for
  969. * the thrown exception
  970. */
  971. function tryCatchReject(f, x, thisArg, next) {
  972. try {
  973. next.become(getHandler(f.call(thisArg, x)));
  974. } catch(e) {
  975. next.become(new Rejected(e));
  976. }
  977. }
  978. /**
  979. * Same as above, but includes the extra argument parameter.
  980. */
  981. function tryCatchReject3(f, x, y, thisArg, next) {
  982. try {
  983. f.call(thisArg, x, y, next);
  984. } catch(e) {
  985. next.become(new Rejected(e));
  986. }
  987. }
  988. /**
  989. * @deprecated
  990. * Return f.call(thisArg, x), or if it throws, *return* the exception
  991. */
  992. function tryCatchReturn(f, x, thisArg, next) {
  993. try {
  994. next.notify(f.call(thisArg, x));
  995. } catch(e) {
  996. next.notify(e);
  997. }
  998. }
  999. function inherit(Parent, Child) {
  1000. Child.prototype = objectCreate(Parent.prototype);
  1001. Child.prototype.constructor = Child;
  1002. }
  1003. function snd(x, y) {
  1004. return y;
  1005. }
  1006. function noop() {}
  1007. return Promise;
  1008. };
  1009. });
  1010. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1011. },{}]},{},[1])
  1012. (1)
  1013. });
  1014. ;