Promise.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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 = this;
  44. this._queueLen = 0;
  45. this._afterQueue = {};
  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' &&
  200. Object.prototype.toString.call(process) === '[object process]';
  201. }
  202. function hasMutationObserver () {
  203. return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
  204. (typeof WebKitMutationObserver !== 'undefined' && 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.message) ? e.stack || e.message : 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 emitRejection = initEmitRejection();
  284. var objectCreate = Object.create ||
  285. function(proto) {
  286. function Child() {}
  287. Child.prototype = proto;
  288. return new Child();
  289. };
  290. /**
  291. * Create a promise whose fate is determined by resolver
  292. * @constructor
  293. * @returns {Promise} promise
  294. * @name Promise
  295. */
  296. function Promise(resolver, handler) {
  297. this._handler = resolver === Handler ? handler : init(resolver);
  298. }
  299. /**
  300. * Run the supplied resolver
  301. * @param resolver
  302. * @returns {Pending}
  303. */
  304. function init(resolver) {
  305. var handler = new Pending();
  306. try {
  307. resolver(promiseResolve, promiseReject, promiseNotify);
  308. } catch (e) {
  309. promiseReject(e);
  310. }
  311. return handler;
  312. /**
  313. * Transition from pre-resolution state to post-resolution state, notifying
  314. * all listeners of the ultimate fulfillment or rejection
  315. * @param {*} x resolution value
  316. */
  317. function promiseResolve (x) {
  318. handler.resolve(x);
  319. }
  320. /**
  321. * Reject this promise with reason, which will be used verbatim
  322. * @param {Error|*} reason rejection reason, strongly suggested
  323. * to be an Error type
  324. */
  325. function promiseReject (reason) {
  326. handler.reject(reason);
  327. }
  328. /**
  329. * @deprecated
  330. * Issue a progress event, notifying all progress listeners
  331. * @param {*} x progress event payload to pass to all listeners
  332. */
  333. function promiseNotify (x) {
  334. handler.notify(x);
  335. }
  336. }
  337. // Creation
  338. Promise.resolve = resolve;
  339. Promise.reject = reject;
  340. Promise.never = never;
  341. Promise._defer = defer;
  342. Promise._handler = getHandler;
  343. /**
  344. * Returns a trusted promise. If x is already a trusted promise, it is
  345. * returned, otherwise returns a new trusted Promise which follows x.
  346. * @param {*} x
  347. * @return {Promise} promise
  348. */
  349. function resolve(x) {
  350. return isPromise(x) ? x
  351. : new Promise(Handler, new Async(getHandler(x)));
  352. }
  353. /**
  354. * Return a reject promise with x as its reason (x is used verbatim)
  355. * @param {*} x
  356. * @returns {Promise} rejected promise
  357. */
  358. function reject(x) {
  359. return new Promise(Handler, new Async(new Rejected(x)));
  360. }
  361. /**
  362. * Return a promise that remains pending forever
  363. * @returns {Promise} forever-pending promise.
  364. */
  365. function never() {
  366. return foreverPendingPromise; // Should be frozen
  367. }
  368. /**
  369. * Creates an internal {promise, resolver} pair
  370. * @private
  371. * @returns {Promise}
  372. */
  373. function defer() {
  374. return new Promise(Handler, new Pending());
  375. }
  376. // Transformation and flow control
  377. /**
  378. * Transform this promise's fulfillment value, returning a new Promise
  379. * for the transformed result. If the promise cannot be fulfilled, onRejected
  380. * is called with the reason. onProgress *may* be called with updates toward
  381. * this promise's fulfillment.
  382. * @param {function=} onFulfilled fulfillment handler
  383. * @param {function=} onRejected rejection handler
  384. * @param {function=} onProgress @deprecated progress handler
  385. * @return {Promise} new promise
  386. */
  387. Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
  388. var parent = this._handler;
  389. var state = parent.join().state();
  390. if ((typeof onFulfilled !== 'function' && state > 0) ||
  391. (typeof onRejected !== 'function' && state < 0)) {
  392. // Short circuit: value will not change, simply share handler
  393. return new this.constructor(Handler, parent);
  394. }
  395. var p = this._beget();
  396. var child = p._handler;
  397. parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
  398. return p;
  399. };
  400. /**
  401. * If this promise cannot be fulfilled due to an error, call onRejected to
  402. * handle the error. Shortcut for .then(undefined, onRejected)
  403. * @param {function?} onRejected
  404. * @return {Promise}
  405. */
  406. Promise.prototype['catch'] = function(onRejected) {
  407. return this.then(void 0, onRejected);
  408. };
  409. /**
  410. * Creates a new, pending promise of the same type as this promise
  411. * @private
  412. * @returns {Promise}
  413. */
  414. Promise.prototype._beget = function() {
  415. return begetFrom(this._handler, this.constructor);
  416. };
  417. function begetFrom(parent, Promise) {
  418. var child = new Pending(parent.receiver, parent.join().context);
  419. return new Promise(Handler, child);
  420. }
  421. // Array combinators
  422. Promise.all = all;
  423. Promise.race = race;
  424. Promise._traverse = traverse;
  425. /**
  426. * Return a promise that will fulfill when all promises in the
  427. * input array have fulfilled, or will reject when one of the
  428. * promises rejects.
  429. * @param {array} promises array of promises
  430. * @returns {Promise} promise for array of fulfillment values
  431. */
  432. function all(promises) {
  433. return traverseWith(snd, null, promises);
  434. }
  435. /**
  436. * Array<Promise<X>> -> Promise<Array<f(X)>>
  437. * @private
  438. * @param {function} f function to apply to each promise's value
  439. * @param {Array} promises array of promises
  440. * @returns {Promise} promise for transformed values
  441. */
  442. function traverse(f, promises) {
  443. return traverseWith(tryCatch2, f, promises);
  444. }
  445. function traverseWith(tryMap, f, promises) {
  446. var handler = typeof f === 'function' ? mapAt : settleAt;
  447. var resolver = new Pending();
  448. var pending = promises.length >>> 0;
  449. var results = new Array(pending);
  450. for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
  451. x = promises[i];
  452. if (x === void 0 && !(i in promises)) {
  453. --pending;
  454. continue;
  455. }
  456. traverseAt(promises, handler, i, x, resolver);
  457. }
  458. if(pending === 0) {
  459. resolver.become(new Fulfilled(results));
  460. }
  461. return new Promise(Handler, resolver);
  462. function mapAt(i, x, resolver) {
  463. if(!resolver.resolved) {
  464. traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
  465. }
  466. }
  467. function settleAt(i, x, resolver) {
  468. results[i] = x;
  469. if(--pending === 0) {
  470. resolver.become(new Fulfilled(results));
  471. }
  472. }
  473. }
  474. function traverseAt(promises, handler, i, x, resolver) {
  475. if (maybeThenable(x)) {
  476. var h = getHandlerMaybeThenable(x);
  477. var s = h.state();
  478. if (s === 0) {
  479. h.fold(handler, i, void 0, resolver);
  480. } else if (s > 0) {
  481. handler(i, h.value, resolver);
  482. } else {
  483. resolver.become(h);
  484. visitRemaining(promises, i+1, h);
  485. }
  486. } else {
  487. handler(i, x, resolver);
  488. }
  489. }
  490. Promise._visitRemaining = visitRemaining;
  491. function visitRemaining(promises, start, handler) {
  492. for(var i=start; i<promises.length; ++i) {
  493. markAsHandled(getHandler(promises[i]), handler);
  494. }
  495. }
  496. function markAsHandled(h, handler) {
  497. if(h === handler) {
  498. return;
  499. }
  500. var s = h.state();
  501. if(s === 0) {
  502. h.visit(h, void 0, h._unreport);
  503. } else if(s < 0) {
  504. h._unreport();
  505. }
  506. }
  507. /**
  508. * Fulfill-reject competitive race. Return a promise that will settle
  509. * to the same state as the earliest input promise to settle.
  510. *
  511. * WARNING: The ES6 Promise spec requires that race()ing an empty array
  512. * must return a promise that is pending forever. This implementation
  513. * returns a singleton forever-pending promise, the same singleton that is
  514. * returned by Promise.never(), thus can be checked with ===
  515. *
  516. * @param {array} promises array of promises to race
  517. * @returns {Promise} if input is non-empty, a promise that will settle
  518. * to the same outcome as the earliest input promise to settle. if empty
  519. * is empty, returns a promise that will never settle.
  520. */
  521. function race(promises) {
  522. if(typeof promises !== 'object' || promises === null) {
  523. return reject(new TypeError('non-iterable passed to race()'));
  524. }
  525. // Sigh, race([]) is untestable unless we return *something*
  526. // that is recognizable without calling .then() on it.
  527. return promises.length === 0 ? never()
  528. : promises.length === 1 ? resolve(promises[0])
  529. : runRace(promises);
  530. }
  531. function runRace(promises) {
  532. var resolver = new Pending();
  533. var i, x, h;
  534. for(i=0; i<promises.length; ++i) {
  535. x = promises[i];
  536. if (x === void 0 && !(i in promises)) {
  537. continue;
  538. }
  539. h = getHandler(x);
  540. if(h.state() !== 0) {
  541. resolver.become(h);
  542. visitRemaining(promises, i+1, h);
  543. break;
  544. } else {
  545. h.visit(resolver, resolver.resolve, resolver.reject);
  546. }
  547. }
  548. return new Promise(Handler, resolver);
  549. }
  550. // Promise internals
  551. // Below this, everything is @private
  552. /**
  553. * Get an appropriate handler for x, without checking for cycles
  554. * @param {*} x
  555. * @returns {object} handler
  556. */
  557. function getHandler(x) {
  558. if(isPromise(x)) {
  559. return x._handler.join();
  560. }
  561. return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
  562. }
  563. /**
  564. * Get a handler for thenable x.
  565. * NOTE: You must only call this if maybeThenable(x) == true
  566. * @param {object|function|Promise} x
  567. * @returns {object} handler
  568. */
  569. function getHandlerMaybeThenable(x) {
  570. return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
  571. }
  572. /**
  573. * Get a handler for potentially untrusted thenable x
  574. * @param {*} x
  575. * @returns {object} handler
  576. */
  577. function getHandlerUntrusted(x) {
  578. try {
  579. var untrustedThen = x.then;
  580. return typeof untrustedThen === 'function'
  581. ? new Thenable(untrustedThen, x)
  582. : new Fulfilled(x);
  583. } catch(e) {
  584. return new Rejected(e);
  585. }
  586. }
  587. /**
  588. * Handler for a promise that is pending forever
  589. * @constructor
  590. */
  591. function Handler() {}
  592. Handler.prototype.when
  593. = Handler.prototype.become
  594. = Handler.prototype.notify // deprecated
  595. = Handler.prototype.fail
  596. = Handler.prototype._unreport
  597. = Handler.prototype._report
  598. = noop;
  599. Handler.prototype._state = 0;
  600. Handler.prototype.state = function() {
  601. return this._state;
  602. };
  603. /**
  604. * Recursively collapse handler chain to find the handler
  605. * nearest to the fully resolved value.
  606. * @returns {object} handler nearest the fully resolved value
  607. */
  608. Handler.prototype.join = function() {
  609. var h = this;
  610. while(h.handler !== void 0) {
  611. h = h.handler;
  612. }
  613. return h;
  614. };
  615. Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
  616. this.when({
  617. resolver: to,
  618. receiver: receiver,
  619. fulfilled: fulfilled,
  620. rejected: rejected,
  621. progress: progress
  622. });
  623. };
  624. Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
  625. this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
  626. };
  627. Handler.prototype.fold = function(f, z, c, to) {
  628. this.when(new Fold(f, z, c, to));
  629. };
  630. /**
  631. * Handler that invokes fail() on any handler it becomes
  632. * @constructor
  633. */
  634. function FailIfRejected() {}
  635. inherit(Handler, FailIfRejected);
  636. FailIfRejected.prototype.become = function(h) {
  637. h.fail();
  638. };
  639. var failIfRejected = new FailIfRejected();
  640. /**
  641. * Handler that manages a queue of consumers waiting on a pending promise
  642. * @constructor
  643. */
  644. function Pending(receiver, inheritedContext) {
  645. Promise.createContext(this, inheritedContext);
  646. this.consumers = void 0;
  647. this.receiver = receiver;
  648. this.handler = void 0;
  649. this.resolved = false;
  650. }
  651. inherit(Handler, Pending);
  652. Pending.prototype._state = 0;
  653. Pending.prototype.resolve = function(x) {
  654. this.become(getHandler(x));
  655. };
  656. Pending.prototype.reject = function(x) {
  657. if(this.resolved) {
  658. return;
  659. }
  660. this.become(new Rejected(x));
  661. };
  662. Pending.prototype.join = function() {
  663. if (!this.resolved) {
  664. return this;
  665. }
  666. var h = this;
  667. while (h.handler !== void 0) {
  668. h = h.handler;
  669. if (h === this) {
  670. return this.handler = cycle();
  671. }
  672. }
  673. return h;
  674. };
  675. Pending.prototype.run = function() {
  676. var q = this.consumers;
  677. var handler = this.handler;
  678. this.handler = this.handler.join();
  679. this.consumers = void 0;
  680. for (var i = 0; i < q.length; ++i) {
  681. handler.when(q[i]);
  682. }
  683. };
  684. Pending.prototype.become = function(handler) {
  685. if(this.resolved) {
  686. return;
  687. }
  688. this.resolved = true;
  689. this.handler = handler;
  690. if(this.consumers !== void 0) {
  691. tasks.enqueue(this);
  692. }
  693. if(this.context !== void 0) {
  694. handler._report(this.context);
  695. }
  696. };
  697. Pending.prototype.when = function(continuation) {
  698. if(this.resolved) {
  699. tasks.enqueue(new ContinuationTask(continuation, this.handler));
  700. } else {
  701. if(this.consumers === void 0) {
  702. this.consumers = [continuation];
  703. } else {
  704. this.consumers.push(continuation);
  705. }
  706. }
  707. };
  708. /**
  709. * @deprecated
  710. */
  711. Pending.prototype.notify = function(x) {
  712. if(!this.resolved) {
  713. tasks.enqueue(new ProgressTask(x, this));
  714. }
  715. };
  716. Pending.prototype.fail = function(context) {
  717. var c = typeof context === 'undefined' ? this.context : context;
  718. this.resolved && this.handler.join().fail(c);
  719. };
  720. Pending.prototype._report = function(context) {
  721. this.resolved && this.handler.join()._report(context);
  722. };
  723. Pending.prototype._unreport = function() {
  724. this.resolved && this.handler.join()._unreport();
  725. };
  726. /**
  727. * Wrap another handler and force it into a future stack
  728. * @param {object} handler
  729. * @constructor
  730. */
  731. function Async(handler) {
  732. this.handler = handler;
  733. }
  734. inherit(Handler, Async);
  735. Async.prototype.when = function(continuation) {
  736. tasks.enqueue(new ContinuationTask(continuation, this));
  737. };
  738. Async.prototype._report = function(context) {
  739. this.join()._report(context);
  740. };
  741. Async.prototype._unreport = function() {
  742. this.join()._unreport();
  743. };
  744. /**
  745. * Handler that wraps an untrusted thenable and assimilates it in a future stack
  746. * @param {function} then
  747. * @param {{then: function}} thenable
  748. * @constructor
  749. */
  750. function Thenable(then, thenable) {
  751. Pending.call(this);
  752. tasks.enqueue(new AssimilateTask(then, thenable, this));
  753. }
  754. inherit(Pending, Thenable);
  755. /**
  756. * Handler for a fulfilled promise
  757. * @param {*} x fulfillment value
  758. * @constructor
  759. */
  760. function Fulfilled(x) {
  761. Promise.createContext(this);
  762. this.value = x;
  763. }
  764. inherit(Handler, Fulfilled);
  765. Fulfilled.prototype._state = 1;
  766. Fulfilled.prototype.fold = function(f, z, c, to) {
  767. runContinuation3(f, z, this, c, to);
  768. };
  769. Fulfilled.prototype.when = function(cont) {
  770. runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
  771. };
  772. var errorId = 0;
  773. /**
  774. * Handler for a rejected promise
  775. * @param {*} x rejection reason
  776. * @constructor
  777. */
  778. function Rejected(x) {
  779. Promise.createContext(this);
  780. this.id = ++errorId;
  781. this.value = x;
  782. this.handled = false;
  783. this.reported = false;
  784. this._report();
  785. }
  786. inherit(Handler, Rejected);
  787. Rejected.prototype._state = -1;
  788. Rejected.prototype.fold = function(f, z, c, to) {
  789. to.become(this);
  790. };
  791. Rejected.prototype.when = function(cont) {
  792. if(typeof cont.rejected === 'function') {
  793. this._unreport();
  794. }
  795. runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
  796. };
  797. Rejected.prototype._report = function(context) {
  798. tasks.afterQueue(new ReportTask(this, context));
  799. };
  800. Rejected.prototype._unreport = function() {
  801. if(this.handled) {
  802. return;
  803. }
  804. this.handled = true;
  805. tasks.afterQueue(new UnreportTask(this));
  806. };
  807. Rejected.prototype.fail = function(context) {
  808. this.reported = true;
  809. emitRejection('unhandledRejection', this);
  810. Promise.onFatalRejection(this, context === void 0 ? this.context : context);
  811. };
  812. function ReportTask(rejection, context) {
  813. this.rejection = rejection;
  814. this.context = context;
  815. }
  816. ReportTask.prototype.run = function() {
  817. if(!this.rejection.handled && !this.rejection.reported) {
  818. this.rejection.reported = true;
  819. emitRejection('unhandledRejection', this.rejection) ||
  820. Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
  821. }
  822. };
  823. function UnreportTask(rejection) {
  824. this.rejection = rejection;
  825. }
  826. UnreportTask.prototype.run = function() {
  827. if(this.rejection.reported) {
  828. emitRejection('rejectionHandled', this.rejection) ||
  829. Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
  830. }
  831. };
  832. // Unhandled rejection hooks
  833. // By default, everything is a noop
  834. Promise.createContext
  835. = Promise.enterContext
  836. = Promise.exitContext
  837. = Promise.onPotentiallyUnhandledRejection
  838. = Promise.onPotentiallyUnhandledRejectionHandled
  839. = Promise.onFatalRejection
  840. = noop;
  841. // Errors and singletons
  842. var foreverPendingHandler = new Handler();
  843. var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
  844. function cycle() {
  845. return new Rejected(new TypeError('Promise cycle'));
  846. }
  847. // Task runners
  848. /**
  849. * Run a single consumer
  850. * @constructor
  851. */
  852. function ContinuationTask(continuation, handler) {
  853. this.continuation = continuation;
  854. this.handler = handler;
  855. }
  856. ContinuationTask.prototype.run = function() {
  857. this.handler.join().when(this.continuation);
  858. };
  859. /**
  860. * Run a queue of progress handlers
  861. * @constructor
  862. */
  863. function ProgressTask(value, handler) {
  864. this.handler = handler;
  865. this.value = value;
  866. }
  867. ProgressTask.prototype.run = function() {
  868. var q = this.handler.consumers;
  869. if(q === void 0) {
  870. return;
  871. }
  872. for (var c, i = 0; i < q.length; ++i) {
  873. c = q[i];
  874. runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
  875. }
  876. };
  877. /**
  878. * Assimilate a thenable, sending it's value to resolver
  879. * @param {function} then
  880. * @param {object|function} thenable
  881. * @param {object} resolver
  882. * @constructor
  883. */
  884. function AssimilateTask(then, thenable, resolver) {
  885. this._then = then;
  886. this.thenable = thenable;
  887. this.resolver = resolver;
  888. }
  889. AssimilateTask.prototype.run = function() {
  890. var h = this.resolver;
  891. tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
  892. function _resolve(x) { h.resolve(x); }
  893. function _reject(x) { h.reject(x); }
  894. function _notify(x) { h.notify(x); }
  895. };
  896. function tryAssimilate(then, thenable, resolve, reject, notify) {
  897. try {
  898. then.call(thenable, resolve, reject, notify);
  899. } catch (e) {
  900. reject(e);
  901. }
  902. }
  903. /**
  904. * Fold a handler value with z
  905. * @constructor
  906. */
  907. function Fold(f, z, c, to) {
  908. this.f = f; this.z = z; this.c = c; this.to = to;
  909. this.resolver = failIfRejected;
  910. this.receiver = this;
  911. }
  912. Fold.prototype.fulfilled = function(x) {
  913. this.f.call(this.c, this.z, x, this.to);
  914. };
  915. Fold.prototype.rejected = function(x) {
  916. this.to.reject(x);
  917. };
  918. Fold.prototype.progress = function(x) {
  919. this.to.notify(x);
  920. };
  921. // Other helpers
  922. /**
  923. * @param {*} x
  924. * @returns {boolean} true iff x is a trusted Promise
  925. */
  926. function isPromise(x) {
  927. return x instanceof Promise;
  928. }
  929. /**
  930. * Test just enough to rule out primitives, in order to take faster
  931. * paths in some code
  932. * @param {*} x
  933. * @returns {boolean} false iff x is guaranteed *not* to be a thenable
  934. */
  935. function maybeThenable(x) {
  936. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  937. }
  938. function runContinuation1(f, h, receiver, next) {
  939. if(typeof f !== 'function') {
  940. return next.become(h);
  941. }
  942. Promise.enterContext(h);
  943. tryCatchReject(f, h.value, receiver, next);
  944. Promise.exitContext();
  945. }
  946. function runContinuation3(f, x, h, receiver, next) {
  947. if(typeof f !== 'function') {
  948. return next.become(h);
  949. }
  950. Promise.enterContext(h);
  951. tryCatchReject3(f, x, h.value, receiver, next);
  952. Promise.exitContext();
  953. }
  954. /**
  955. * @deprecated
  956. */
  957. function runNotify(f, x, h, receiver, next) {
  958. if(typeof f !== 'function') {
  959. return next.notify(x);
  960. }
  961. Promise.enterContext(h);
  962. tryCatchReturn(f, x, receiver, next);
  963. Promise.exitContext();
  964. }
  965. function tryCatch2(f, a, b) {
  966. try {
  967. return f(a, b);
  968. } catch(e) {
  969. return reject(e);
  970. }
  971. }
  972. /**
  973. * Return f.call(thisArg, x), or if it throws return a rejected promise for
  974. * the thrown exception
  975. */
  976. function tryCatchReject(f, x, thisArg, next) {
  977. try {
  978. next.become(getHandler(f.call(thisArg, x)));
  979. } catch(e) {
  980. next.become(new Rejected(e));
  981. }
  982. }
  983. /**
  984. * Same as above, but includes the extra argument parameter.
  985. */
  986. function tryCatchReject3(f, x, y, thisArg, next) {
  987. try {
  988. f.call(thisArg, x, y, next);
  989. } catch(e) {
  990. next.become(new Rejected(e));
  991. }
  992. }
  993. /**
  994. * @deprecated
  995. * Return f.call(thisArg, x), or if it throws, *return* the exception
  996. */
  997. function tryCatchReturn(f, x, thisArg, next) {
  998. try {
  999. next.notify(f.call(thisArg, x));
  1000. } catch(e) {
  1001. next.notify(e);
  1002. }
  1003. }
  1004. function inherit(Parent, Child) {
  1005. Child.prototype = objectCreate(Parent.prototype);
  1006. Child.prototype.constructor = Child;
  1007. }
  1008. function snd(x, y) {
  1009. return y;
  1010. }
  1011. function noop() {}
  1012. function hasCustomEvent() {
  1013. if(typeof CustomEvent === 'function') {
  1014. try {
  1015. var ev = new CustomEvent('unhandledRejection');
  1016. return ev instanceof CustomEvent;
  1017. } catch (ignoredException) {}
  1018. }
  1019. return false;
  1020. }
  1021. function hasInternetExplorerCustomEvent() {
  1022. if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
  1023. try {
  1024. // Try to create one event to make sure it's supported
  1025. var ev = document.createEvent('CustomEvent');
  1026. ev.initCustomEvent('eventType', false, true, {});
  1027. return true;
  1028. } catch (ignoredException) {}
  1029. }
  1030. return false;
  1031. }
  1032. function initEmitRejection() {
  1033. /*global process, self, CustomEvent*/
  1034. if(typeof process !== 'undefined' && process !== null
  1035. && typeof process.emit === 'function') {
  1036. // Returning falsy here means to call the default
  1037. // onPotentiallyUnhandledRejection API. This is safe even in
  1038. // browserify since process.emit always returns falsy in browserify:
  1039. // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
  1040. return function(type, rejection) {
  1041. return type === 'unhandledRejection'
  1042. ? process.emit(type, rejection.value, rejection)
  1043. : process.emit(type, rejection);
  1044. };
  1045. } else if(typeof self !== 'undefined' && hasCustomEvent()) {
  1046. return (function (self, CustomEvent) {
  1047. return function (type, rejection) {
  1048. var ev = new CustomEvent(type, {
  1049. detail: {
  1050. reason: rejection.value,
  1051. key: rejection
  1052. },
  1053. bubbles: false,
  1054. cancelable: true
  1055. });
  1056. return !self.dispatchEvent(ev);
  1057. };
  1058. }(self, CustomEvent));
  1059. } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
  1060. return (function(self, document) {
  1061. return function(type, rejection) {
  1062. var ev = document.createEvent('CustomEvent');
  1063. ev.initCustomEvent(type, false, true, {
  1064. reason: rejection.value,
  1065. key: rejection
  1066. });
  1067. return !self.dispatchEvent(ev);
  1068. };
  1069. }(self, document));
  1070. }
  1071. return noop;
  1072. }
  1073. return Promise;
  1074. };
  1075. });
  1076. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1077. },{}]},{},[1])
  1078. //# sourceMappingURL=Promise.js.map
  1079. (1)
  1080. });
  1081. ;