es6-promise.js 32 KB

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