es6-promise.js 32 KB

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