es6-promise.auto.js 28 KB

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