Version 1
[yaffs-website] / node_modules / es6-promise / dist / es6-promise.auto.js
1 /*!
2  * @overview es6-promise - a tiny implementation of Promises/A+.
3  * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
4  * @license   Licensed under MIT license
5  *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
6  * @version   4.0.5
7  */
8
9 (function (global, factory) {
10     typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
11     typeof define === 'function' && define.amd ? define(factory) :
12     (global.ES6Promise = factory());
13 }(this, (function () { 'use strict';
14
15 function objectOrFunction(x) {
16   return typeof x === 'function' || typeof x === 'object' && x !== null;
17 }
18
19 function isFunction(x) {
20   return typeof x === 'function';
21 }
22
23 var _isArray = undefined;
24 if (!Array.isArray) {
25   _isArray = function (x) {
26     return Object.prototype.toString.call(x) === '[object Array]';
27   };
28 } else {
29   _isArray = Array.isArray;
30 }
31
32 var isArray = _isArray;
33
34 var len = 0;
35 var vertxNext = undefined;
36 var customSchedulerFn = undefined;
37
38 var asap = function asap(callback, arg) {
39   queue[len] = callback;
40   queue[len + 1] = arg;
41   len += 2;
42   if (len === 2) {
43     // If len is 2, that means that we need to schedule an async flush.
44     // If additional callbacks are queued before the queue is flushed, they
45     // will be processed by this flush that we are scheduling.
46     if (customSchedulerFn) {
47       customSchedulerFn(flush);
48     } else {
49       scheduleFlush();
50     }
51   }
52 };
53
54 function setScheduler(scheduleFn) {
55   customSchedulerFn = scheduleFn;
56 }
57
58 function setAsap(asapFn) {
59   asap = asapFn;
60 }
61
62 var browserWindow = typeof window !== 'undefined' ? window : undefined;
63 var browserGlobal = browserWindow || {};
64 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
65 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
66
67 // test for web worker but not in IE10
68 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
69
70 // node
71 function useNextTick() {
72   // node version 0.10.x displays a deprecation warning when nextTick is used recursively
73   // see https://github.com/cujojs/when/issues/410 for details
74   return function () {
75     return process.nextTick(flush);
76   };
77 }
78
79 // vertx
80 function useVertxTimer() {
81   if (typeof vertxNext !== 'undefined') {
82     return function () {
83       vertxNext(flush);
84     };
85   }
86
87   return useSetTimeout();
88 }
89
90 function useMutationObserver() {
91   var iterations = 0;
92   var observer = new BrowserMutationObserver(flush);
93   var node = document.createTextNode('');
94   observer.observe(node, { characterData: true });
95
96   return function () {
97     node.data = iterations = ++iterations % 2;
98   };
99 }
100
101 // web worker
102 function useMessageChannel() {
103   var channel = new MessageChannel();
104   channel.port1.onmessage = flush;
105   return function () {
106     return channel.port2.postMessage(0);
107   };
108 }
109
110 function useSetTimeout() {
111   // Store setTimeout reference so es6-promise will be unaffected by
112   // other code modifying setTimeout (like sinon.useFakeTimers())
113   var globalSetTimeout = setTimeout;
114   return function () {
115     return globalSetTimeout(flush, 1);
116   };
117 }
118
119 var queue = new Array(1000);
120 function flush() {
121   for (var i = 0; i < len; i += 2) {
122     var callback = queue[i];
123     var arg = queue[i + 1];
124
125     callback(arg);
126
127     queue[i] = undefined;
128     queue[i + 1] = undefined;
129   }
130
131   len = 0;
132 }
133
134 function attemptVertx() {
135   try {
136     var r = require;
137     var vertx = r('vertx');
138     vertxNext = vertx.runOnLoop || vertx.runOnContext;
139     return useVertxTimer();
140   } catch (e) {
141     return useSetTimeout();
142   }
143 }
144
145 var scheduleFlush = undefined;
146 // Decide what async method to use to triggering processing of queued callbacks:
147 if (isNode) {
148   scheduleFlush = useNextTick();
149 } else if (BrowserMutationObserver) {
150   scheduleFlush = useMutationObserver();
151 } else if (isWorker) {
152   scheduleFlush = useMessageChannel();
153 } else if (browserWindow === undefined && typeof require === 'function') {
154   scheduleFlush = attemptVertx();
155 } else {
156   scheduleFlush = useSetTimeout();
157 }
158
159 function then(onFulfillment, onRejection) {
160   var _arguments = arguments;
161
162   var parent = this;
163
164   var child = new this.constructor(noop);
165
166   if (child[PROMISE_ID] === undefined) {
167     makePromise(child);
168   }
169
170   var _state = parent._state;
171
172   if (_state) {
173     (function () {
174       var callback = _arguments[_state - 1];
175       asap(function () {
176         return invokeCallback(_state, child, callback, parent._result);
177       });
178     })();
179   } else {
180     subscribe(parent, child, onFulfillment, onRejection);
181   }
182
183   return child;
184 }
185
186 /**
187   `Promise.resolve` returns a promise that will become resolved with the
188   passed `value`. It is shorthand for the following:
189
190   ```javascript
191   let promise = new Promise(function(resolve, reject){
192     resolve(1);
193   });
194
195   promise.then(function(value){
196     // value === 1
197   });
198   ```
199
200   Instead of writing the above, your code now simply becomes the following:
201
202   ```javascript
203   let promise = Promise.resolve(1);
204
205   promise.then(function(value){
206     // value === 1
207   });
208   ```
209
210   @method resolve
211   @static
212   @param {Any} value value that the returned promise will be resolved with
213   Useful for tooling.
214   @return {Promise} a promise that will become fulfilled with the given
215   `value`
216 */
217 function resolve(object) {
218   /*jshint validthis:true */
219   var Constructor = this;
220
221   if (object && typeof object === 'object' && object.constructor === Constructor) {
222     return object;
223   }
224
225   var promise = new Constructor(noop);
226   _resolve(promise, object);
227   return promise;
228 }
229
230 var PROMISE_ID = Math.random().toString(36).substring(16);
231
232 function noop() {}
233
234 var PENDING = void 0;
235 var FULFILLED = 1;
236 var REJECTED = 2;
237
238 var GET_THEN_ERROR = new ErrorObject();
239
240 function selfFulfillment() {
241   return new TypeError("You cannot resolve a promise with itself");
242 }
243
244 function cannotReturnOwn() {
245   return new TypeError('A promises callback cannot return that same promise.');
246 }
247
248 function getThen(promise) {
249   try {
250     return promise.then;
251   } catch (error) {
252     GET_THEN_ERROR.error = error;
253     return GET_THEN_ERROR;
254   }
255 }
256
257 function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
258   try {
259     then.call(value, fulfillmentHandler, rejectionHandler);
260   } catch (e) {
261     return e;
262   }
263 }
264
265 function handleForeignThenable(promise, thenable, then) {
266   asap(function (promise) {
267     var sealed = false;
268     var error = tryThen(then, thenable, function (value) {
269       if (sealed) {
270         return;
271       }
272       sealed = true;
273       if (thenable !== value) {
274         _resolve(promise, value);
275       } else {
276         fulfill(promise, value);
277       }
278     }, function (reason) {
279       if (sealed) {
280         return;
281       }
282       sealed = true;
283
284       _reject(promise, reason);
285     }, 'Settle: ' + (promise._label || ' unknown promise'));
286
287     if (!sealed && error) {
288       sealed = true;
289       _reject(promise, error);
290     }
291   }, promise);
292 }
293
294 function handleOwnThenable(promise, thenable) {
295   if (thenable._state === FULFILLED) {
296     fulfill(promise, thenable._result);
297   } else if (thenable._state === REJECTED) {
298     _reject(promise, thenable._result);
299   } else {
300     subscribe(thenable, undefined, function (value) {
301       return _resolve(promise, value);
302     }, function (reason) {
303       return _reject(promise, reason);
304     });
305   }
306 }
307
308 function handleMaybeThenable(promise, maybeThenable, then$$) {
309   if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
310     handleOwnThenable(promise, maybeThenable);
311   } else {
312     if (then$$ === GET_THEN_ERROR) {
313       _reject(promise, GET_THEN_ERROR.error);
314     } else if (then$$ === undefined) {
315       fulfill(promise, maybeThenable);
316     } else if (isFunction(then$$)) {
317       handleForeignThenable(promise, maybeThenable, then$$);
318     } else {
319       fulfill(promise, maybeThenable);
320     }
321   }
322 }
323
324 function _resolve(promise, value) {
325   if (promise === value) {
326     _reject(promise, selfFulfillment());
327   } else if (objectOrFunction(value)) {
328     handleMaybeThenable(promise, value, getThen(value));
329   } else {
330     fulfill(promise, value);
331   }
332 }
333
334 function publishRejection(promise) {
335   if (promise._onerror) {
336     promise._onerror(promise._result);
337   }
338
339   publish(promise);
340 }
341
342 function fulfill(promise, value) {
343   if (promise._state !== PENDING) {
344     return;
345   }
346
347   promise._result = value;
348   promise._state = FULFILLED;
349
350   if (promise._subscribers.length !== 0) {
351     asap(publish, promise);
352   }
353 }
354
355 function _reject(promise, reason) {
356   if (promise._state !== PENDING) {
357     return;
358   }
359   promise._state = REJECTED;
360   promise._result = reason;
361
362   asap(publishRejection, promise);
363 }
364
365 function subscribe(parent, child, onFulfillment, onRejection) {
366   var _subscribers = parent._subscribers;
367   var length = _subscribers.length;
368
369   parent._onerror = null;
370
371   _subscribers[length] = child;
372   _subscribers[length + FULFILLED] = onFulfillment;
373   _subscribers[length + REJECTED] = onRejection;
374
375   if (length === 0 && parent._state) {
376     asap(publish, parent);
377   }
378 }
379
380 function publish(promise) {
381   var subscribers = promise._subscribers;
382   var settled = promise._state;
383
384   if (subscribers.length === 0) {
385     return;
386   }
387
388   var child = undefined,
389       callback = undefined,
390       detail = promise._result;
391
392   for (var i = 0; i < subscribers.length; i += 3) {
393     child = subscribers[i];
394     callback = subscribers[i + settled];
395
396     if (child) {
397       invokeCallback(settled, child, callback, detail);
398     } else {
399       callback(detail);
400     }
401   }
402
403   promise._subscribers.length = 0;
404 }
405
406 function ErrorObject() {
407   this.error = null;
408 }
409
410 var TRY_CATCH_ERROR = new ErrorObject();
411
412 function tryCatch(callback, detail) {
413   try {
414     return callback(detail);
415   } catch (e) {
416     TRY_CATCH_ERROR.error = e;
417     return TRY_CATCH_ERROR;
418   }
419 }
420
421 function invokeCallback(settled, promise, callback, detail) {
422   var hasCallback = isFunction(callback),
423       value = undefined,
424       error = undefined,
425       succeeded = undefined,
426       failed = undefined;
427
428   if (hasCallback) {
429     value = tryCatch(callback, detail);
430
431     if (value === TRY_CATCH_ERROR) {
432       failed = true;
433       error = value.error;
434       value = null;
435     } else {
436       succeeded = true;
437     }
438
439     if (promise === value) {
440       _reject(promise, cannotReturnOwn());
441       return;
442     }
443   } else {
444     value = detail;
445     succeeded = true;
446   }
447
448   if (promise._state !== PENDING) {
449     // noop
450   } else if (hasCallback && succeeded) {
451       _resolve(promise, value);
452     } else if (failed) {
453       _reject(promise, error);
454     } else if (settled === FULFILLED) {
455       fulfill(promise, value);
456     } else if (settled === REJECTED) {
457       _reject(promise, value);
458     }
459 }
460
461 function initializePromise(promise, resolver) {
462   try {
463     resolver(function resolvePromise(value) {
464       _resolve(promise, value);
465     }, function rejectPromise(reason) {
466       _reject(promise, reason);
467     });
468   } catch (e) {
469     _reject(promise, e);
470   }
471 }
472
473 var id = 0;
474 function nextId() {
475   return id++;
476 }
477
478 function makePromise(promise) {
479   promise[PROMISE_ID] = id++;
480   promise._state = undefined;
481   promise._result = undefined;
482   promise._subscribers = [];
483 }
484
485 function Enumerator(Constructor, input) {
486   this._instanceConstructor = Constructor;
487   this.promise = new Constructor(noop);
488
489   if (!this.promise[PROMISE_ID]) {
490     makePromise(this.promise);
491   }
492
493   if (isArray(input)) {
494     this._input = input;
495     this.length = input.length;
496     this._remaining = input.length;
497
498     this._result = new Array(this.length);
499
500     if (this.length === 0) {
501       fulfill(this.promise, this._result);
502     } else {
503       this.length = this.length || 0;
504       this._enumerate();
505       if (this._remaining === 0) {
506         fulfill(this.promise, this._result);
507       }
508     }
509   } else {
510     _reject(this.promise, validationError());
511   }
512 }
513
514 function validationError() {
515   return new Error('Array Methods must be provided an Array');
516 };
517
518 Enumerator.prototype._enumerate = function () {
519   var length = this.length;
520   var _input = this._input;
521
522   for (var i = 0; this._state === PENDING && i < length; i++) {
523     this._eachEntry(_input[i], i);
524   }
525 };
526
527 Enumerator.prototype._eachEntry = function (entry, i) {
528   var c = this._instanceConstructor;
529   var resolve$$ = c.resolve;
530
531   if (resolve$$ === resolve) {
532     var _then = getThen(entry);
533
534     if (_then === then && entry._state !== PENDING) {
535       this._settledAt(entry._state, i, entry._result);
536     } else if (typeof _then !== 'function') {
537       this._remaining--;
538       this._result[i] = entry;
539     } else if (c === Promise) {
540       var promise = new c(noop);
541       handleMaybeThenable(promise, entry, _then);
542       this._willSettleAt(promise, i);
543     } else {
544       this._willSettleAt(new c(function (resolve$$) {
545         return resolve$$(entry);
546       }), i);
547     }
548   } else {
549     this._willSettleAt(resolve$$(entry), i);
550   }
551 };
552
553 Enumerator.prototype._settledAt = function (state, i, value) {
554   var promise = this.promise;
555
556   if (promise._state === PENDING) {
557     this._remaining--;
558
559     if (state === REJECTED) {
560       _reject(promise, value);
561     } else {
562       this._result[i] = value;
563     }
564   }
565
566   if (this._remaining === 0) {
567     fulfill(promise, this._result);
568   }
569 };
570
571 Enumerator.prototype._willSettleAt = function (promise, i) {
572   var enumerator = this;
573
574   subscribe(promise, undefined, function (value) {
575     return enumerator._settledAt(FULFILLED, i, value);
576   }, function (reason) {
577     return enumerator._settledAt(REJECTED, i, reason);
578   });
579 };
580
581 /**
582   `Promise.all` accepts an array of promises, and returns a new promise which
583   is fulfilled with an array of fulfillment values for the passed promises, or
584   rejected with the reason of the first passed promise to be rejected. It casts all
585   elements of the passed iterable to promises as it runs this algorithm.
586
587   Example:
588
589   ```javascript
590   let promise1 = resolve(1);
591   let promise2 = resolve(2);
592   let promise3 = resolve(3);
593   let promises = [ promise1, promise2, promise3 ];
594
595   Promise.all(promises).then(function(array){
596     // The array here would be [ 1, 2, 3 ];
597   });
598   ```
599
600   If any of the `promises` given to `all` are rejected, the first promise
601   that is rejected will be given as an argument to the returned promises's
602   rejection handler. For example:
603
604   Example:
605
606   ```javascript
607   let promise1 = resolve(1);
608   let promise2 = reject(new Error("2"));
609   let promise3 = reject(new Error("3"));
610   let promises = [ promise1, promise2, promise3 ];
611
612   Promise.all(promises).then(function(array){
613     // Code here never runs because there are rejected promises!
614   }, function(error) {
615     // error.message === "2"
616   });
617   ```
618
619   @method all
620   @static
621   @param {Array} entries array of promises
622   @param {String} label optional string for labeling the promise.
623   Useful for tooling.
624   @return {Promise} promise that is fulfilled when all `promises` have been
625   fulfilled, or rejected if any of them become rejected.
626   @static
627 */
628 function all(entries) {
629   return new Enumerator(this, entries).promise;
630 }
631
632 /**
633   `Promise.race` returns a new promise which is settled in the same way as the
634   first passed promise to settle.
635
636   Example:
637
638   ```javascript
639   let promise1 = new Promise(function(resolve, reject){
640     setTimeout(function(){
641       resolve('promise 1');
642     }, 200);
643   });
644
645   let promise2 = new Promise(function(resolve, reject){
646     setTimeout(function(){
647       resolve('promise 2');
648     }, 100);
649   });
650
651   Promise.race([promise1, promise2]).then(function(result){
652     // result === 'promise 2' because it was resolved before promise1
653     // was resolved.
654   });
655   ```
656
657   `Promise.race` is deterministic in that only the state of the first
658   settled promise matters. For example, even if other promises given to the
659   `promises` array argument are resolved, but the first settled promise has
660   become rejected before the other promises became fulfilled, the returned
661   promise will become rejected:
662
663   ```javascript
664   let promise1 = new Promise(function(resolve, reject){
665     setTimeout(function(){
666       resolve('promise 1');
667     }, 200);
668   });
669
670   let promise2 = new Promise(function(resolve, reject){
671     setTimeout(function(){
672       reject(new Error('promise 2'));
673     }, 100);
674   });
675
676   Promise.race([promise1, promise2]).then(function(result){
677     // Code here never runs
678   }, function(reason){
679     // reason.message === 'promise 2' because promise 2 became rejected before
680     // promise 1 became fulfilled
681   });
682   ```
683
684   An example real-world use case is implementing timeouts:
685
686   ```javascript
687   Promise.race([ajax('foo.json'), timeout(5000)])
688   ```
689
690   @method race
691   @static
692   @param {Array} promises array of promises to observe
693   Useful for tooling.
694   @return {Promise} a promise which settles in the same way as the first passed
695   promise to settle.
696 */
697 function race(entries) {
698   /*jshint validthis:true */
699   var Constructor = this;
700
701   if (!isArray(entries)) {
702     return new Constructor(function (_, reject) {
703       return reject(new TypeError('You must pass an array to race.'));
704     });
705   } else {
706     return new Constructor(function (resolve, reject) {
707       var length = entries.length;
708       for (var i = 0; i < length; i++) {
709         Constructor.resolve(entries[i]).then(resolve, reject);
710       }
711     });
712   }
713 }
714
715 /**
716   `Promise.reject` returns a promise rejected with the passed `reason`.
717   It is shorthand for the following:
718
719   ```javascript
720   let promise = new Promise(function(resolve, reject){
721     reject(new Error('WHOOPS'));
722   });
723
724   promise.then(function(value){
725     // Code here doesn't run because the promise is rejected!
726   }, function(reason){
727     // reason.message === 'WHOOPS'
728   });
729   ```
730
731   Instead of writing the above, your code now simply becomes the following:
732
733   ```javascript
734   let promise = Promise.reject(new Error('WHOOPS'));
735
736   promise.then(function(value){
737     // Code here doesn't run because the promise is rejected!
738   }, function(reason){
739     // reason.message === 'WHOOPS'
740   });
741   ```
742
743   @method reject
744   @static
745   @param {Any} reason value that the returned promise will be rejected with.
746   Useful for tooling.
747   @return {Promise} a promise rejected with the given `reason`.
748 */
749 function reject(reason) {
750   /*jshint validthis:true */
751   var Constructor = this;
752   var promise = new Constructor(noop);
753   _reject(promise, reason);
754   return promise;
755 }
756
757 function needsResolver() {
758   throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
759 }
760
761 function needsNew() {
762   throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
763 }
764
765 /**
766   Promise objects represent the eventual result of an asynchronous operation. The
767   primary way of interacting with a promise is through its `then` method, which
768   registers callbacks to receive either a promise's eventual value or the reason
769   why the promise cannot be fulfilled.
770
771   Terminology
772   -----------
773
774   - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
775   - `thenable` is an object or function that defines a `then` method.
776   - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
777   - `exception` is a value that is thrown using the throw statement.
778   - `reason` is a value that indicates why a promise was rejected.
779   - `settled` the final resting state of a promise, fulfilled or rejected.
780
781   A promise can be in one of three states: pending, fulfilled, or rejected.
782
783   Promises that are fulfilled have a fulfillment value and are in the fulfilled
784   state.  Promises that are rejected have a rejection reason and are in the
785   rejected state.  A fulfillment value is never a thenable.
786
787   Promises can also be said to *resolve* a value.  If this value is also a
788   promise, then the original promise's settled state will match the value's
789   settled state.  So a promise that *resolves* a promise that rejects will
790   itself reject, and a promise that *resolves* a promise that fulfills will
791   itself fulfill.
792
793
794   Basic Usage:
795   ------------
796
797   ```js
798   let promise = new Promise(function(resolve, reject) {
799     // on success
800     resolve(value);
801
802     // on failure
803     reject(reason);
804   });
805
806   promise.then(function(value) {
807     // on fulfillment
808   }, function(reason) {
809     // on rejection
810   });
811   ```
812
813   Advanced Usage:
814   ---------------
815
816   Promises shine when abstracting away asynchronous interactions such as
817   `XMLHttpRequest`s.
818
819   ```js
820   function getJSON(url) {
821     return new Promise(function(resolve, reject){
822       let xhr = new XMLHttpRequest();
823
824       xhr.open('GET', url);
825       xhr.onreadystatechange = handler;
826       xhr.responseType = 'json';
827       xhr.setRequestHeader('Accept', 'application/json');
828       xhr.send();
829
830       function handler() {
831         if (this.readyState === this.DONE) {
832           if (this.status === 200) {
833             resolve(this.response);
834           } else {
835             reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
836           }
837         }
838       };
839     });
840   }
841
842   getJSON('/posts.json').then(function(json) {
843     // on fulfillment
844   }, function(reason) {
845     // on rejection
846   });
847   ```
848
849   Unlike callbacks, promises are great composable primitives.
850
851   ```js
852   Promise.all([
853     getJSON('/posts'),
854     getJSON('/comments')
855   ]).then(function(values){
856     values[0] // => postsJSON
857     values[1] // => commentsJSON
858
859     return values;
860   });
861   ```
862
863   @class Promise
864   @param {function} resolver
865   Useful for tooling.
866   @constructor
867 */
868 function Promise(resolver) {
869   this[PROMISE_ID] = nextId();
870   this._result = this._state = undefined;
871   this._subscribers = [];
872
873   if (noop !== resolver) {
874     typeof resolver !== 'function' && needsResolver();
875     this instanceof Promise ? initializePromise(this, resolver) : needsNew();
876   }
877 }
878
879 Promise.all = all;
880 Promise.race = race;
881 Promise.resolve = resolve;
882 Promise.reject = reject;
883 Promise._setScheduler = setScheduler;
884 Promise._setAsap = setAsap;
885 Promise._asap = asap;
886
887 Promise.prototype = {
888   constructor: Promise,
889
890   /**
891     The primary way of interacting with a promise is through its `then` method,
892     which registers callbacks to receive either a promise's eventual value or the
893     reason why the promise cannot be fulfilled.
894   
895     ```js
896     findUser().then(function(user){
897       // user is available
898     }, function(reason){
899       // user is unavailable, and you are given the reason why
900     });
901     ```
902   
903     Chaining
904     --------
905   
906     The return value of `then` is itself a promise.  This second, 'downstream'
907     promise is resolved with the return value of the first promise's fulfillment
908     or rejection handler, or rejected if the handler throws an exception.
909   
910     ```js
911     findUser().then(function (user) {
912       return user.name;
913     }, function (reason) {
914       return 'default name';
915     }).then(function (userName) {
916       // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
917       // will be `'default name'`
918     });
919   
920     findUser().then(function (user) {
921       throw new Error('Found user, but still unhappy');
922     }, function (reason) {
923       throw new Error('`findUser` rejected and we're unhappy');
924     }).then(function (value) {
925       // never reached
926     }, function (reason) {
927       // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
928       // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
929     });
930     ```
931     If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
932   
933     ```js
934     findUser().then(function (user) {
935       throw new PedagogicalException('Upstream error');
936     }).then(function (value) {
937       // never reached
938     }).then(function (value) {
939       // never reached
940     }, function (reason) {
941       // The `PedgagocialException` is propagated all the way down to here
942     });
943     ```
944   
945     Assimilation
946     ------------
947   
948     Sometimes the value you want to propagate to a downstream promise can only be
949     retrieved asynchronously. This can be achieved by returning a promise in the
950     fulfillment or rejection handler. The downstream promise will then be pending
951     until the returned promise is settled. This is called *assimilation*.
952   
953     ```js
954     findUser().then(function (user) {
955       return findCommentsByAuthor(user);
956     }).then(function (comments) {
957       // The user's comments are now available
958     });
959     ```
960   
961     If the assimliated promise rejects, then the downstream promise will also reject.
962   
963     ```js
964     findUser().then(function (user) {
965       return findCommentsByAuthor(user);
966     }).then(function (comments) {
967       // If `findCommentsByAuthor` fulfills, we'll have the value here
968     }, function (reason) {
969       // If `findCommentsByAuthor` rejects, we'll have the reason here
970     });
971     ```
972   
973     Simple Example
974     --------------
975   
976     Synchronous Example
977   
978     ```javascript
979     let result;
980   
981     try {
982       result = findResult();
983       // success
984     } catch(reason) {
985       // failure
986     }
987     ```
988   
989     Errback Example
990   
991     ```js
992     findResult(function(result, err){
993       if (err) {
994         // failure
995       } else {
996         // success
997       }
998     });
999     ```
1000   
1001     Promise Example;
1002   
1003     ```javascript
1004     findResult().then(function(result){
1005       // success
1006     }, function(reason){
1007       // failure
1008     });
1009     ```
1010   
1011     Advanced Example
1012     --------------
1013   
1014     Synchronous Example
1015   
1016     ```javascript
1017     let author, books;
1018   
1019     try {
1020       author = findAuthor();
1021       books  = findBooksByAuthor(author);
1022       // success
1023     } catch(reason) {
1024       // failure
1025     }
1026     ```
1027   
1028     Errback Example
1029   
1030     ```js
1031   
1032     function foundBooks(books) {
1033   
1034     }
1035   
1036     function failure(reason) {
1037   
1038     }
1039   
1040     findAuthor(function(author, err){
1041       if (err) {
1042         failure(err);
1043         // failure
1044       } else {
1045         try {
1046           findBoooksByAuthor(author, function(books, err) {
1047             if (err) {
1048               failure(err);
1049             } else {
1050               try {
1051                 foundBooks(books);
1052               } catch(reason) {
1053                 failure(reason);
1054               }
1055             }
1056           });
1057         } catch(error) {
1058           failure(err);
1059         }
1060         // success
1061       }
1062     });
1063     ```
1064   
1065     Promise Example;
1066   
1067     ```javascript
1068     findAuthor().
1069       then(findBooksByAuthor).
1070       then(function(books){
1071         // found books
1072     }).catch(function(reason){
1073       // something went wrong
1074     });
1075     ```
1076   
1077     @method then
1078     @param {Function} onFulfilled
1079     @param {Function} onRejected
1080     Useful for tooling.
1081     @return {Promise}
1082   */
1083   then: then,
1084
1085   /**
1086     `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
1087     as the catch block of a try/catch statement.
1088   
1089     ```js
1090     function findAuthor(){
1091       throw new Error('couldn't find that author');
1092     }
1093   
1094     // synchronous
1095     try {
1096       findAuthor();
1097     } catch(reason) {
1098       // something went wrong
1099     }
1100   
1101     // async with promises
1102     findAuthor().catch(function(reason){
1103       // something went wrong
1104     });
1105     ```
1106   
1107     @method catch
1108     @param {Function} onRejection
1109     Useful for tooling.
1110     @return {Promise}
1111   */
1112   'catch': function _catch(onRejection) {
1113     return this.then(null, onRejection);
1114   }
1115 };
1116
1117 function polyfill() {
1118     var local = undefined;
1119
1120     if (typeof global !== 'undefined') {
1121         local = global;
1122     } else if (typeof self !== 'undefined') {
1123         local = self;
1124     } else {
1125         try {
1126             local = Function('return this')();
1127         } catch (e) {
1128             throw new Error('polyfill failed because global object is unavailable in this environment');
1129         }
1130     }
1131
1132     var P = local.Promise;
1133
1134     if (P) {
1135         var promiseToString = null;
1136         try {
1137             promiseToString = Object.prototype.toString.call(P.resolve());
1138         } catch (e) {
1139             // silently ignored
1140         }
1141
1142         if (promiseToString === '[object Promise]' && !P.cast) {
1143             return;
1144         }
1145     }
1146
1147     local.Promise = Promise;
1148 }
1149
1150 // Strange compat..
1151 Promise.polyfill = polyfill;
1152 Promise.Promise = Promise;
1153
1154 return Promise;
1155
1156 })));
1157
1158 ES6Promise.polyfill();
1159 //# sourceMappingURL=es6-promise.auto.map