es6-promise.js 31 KB

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