es6-promise.auto.js 31 KB

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