You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

es6-promise.auto.js 29KB

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