UNPKG

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