es6-promise.js 29 KB

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