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