es6-promise.js 28 KB

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