rsvp.es.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474
  1. /*!
  2. * @overview RSVP - a tiny implementation of Promises/A+.
  3. * @copyright Copyright (c) 2016 Yehuda Katz, Tom Dale, Stefan Penner and contributors
  4. * @license Licensed under MIT license
  5. * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE
  6. * @version 4.8.4+ff10049b
  7. */
  8. function callbacksFor(object) {
  9. let callbacks = object._promiseCallbacks;
  10. if (!callbacks) {
  11. callbacks = object._promiseCallbacks = {};
  12. }
  13. return callbacks;
  14. }
  15. /**
  16. @class EventTarget
  17. @for rsvp
  18. @public
  19. */
  20. var EventTarget = {
  21. /**
  22. `EventTarget.mixin` extends an object with EventTarget methods. For
  23. Example:
  24. ```javascript
  25. import EventTarget from 'rsvp';
  26. let object = {};
  27. EventTarget.mixin(object);
  28. object.on('finished', function(event) {
  29. // handle event
  30. });
  31. object.trigger('finished', { detail: value });
  32. ```
  33. `EventTarget.mixin` also works with prototypes:
  34. ```javascript
  35. import EventTarget from 'rsvp';
  36. let Person = function() {};
  37. EventTarget.mixin(Person.prototype);
  38. let yehuda = new Person();
  39. let tom = new Person();
  40. yehuda.on('poke', function(event) {
  41. console.log('Yehuda says OW');
  42. });
  43. tom.on('poke', function(event) {
  44. console.log('Tom says OW');
  45. });
  46. yehuda.trigger('poke');
  47. tom.trigger('poke');
  48. ```
  49. @method mixin
  50. @for rsvp
  51. @private
  52. @param {Object} object object to extend with EventTarget methods
  53. */
  54. mixin(object) {
  55. object.on = this.on;
  56. object.off = this.off;
  57. object.trigger = this.trigger;
  58. object._promiseCallbacks = undefined;
  59. return object;
  60. },
  61. /**
  62. Registers a callback to be executed when `eventName` is triggered
  63. ```javascript
  64. object.on('event', function(eventInfo){
  65. // handle the event
  66. });
  67. object.trigger('event');
  68. ```
  69. @method on
  70. @for EventTarget
  71. @private
  72. @param {String} eventName name of the event to listen for
  73. @param {Function} callback function to be called when the event is triggered.
  74. */
  75. on(eventName, callback) {
  76. if (typeof callback !== 'function') {
  77. throw new TypeError('Callback must be a function');
  78. }
  79. let allCallbacks = callbacksFor(this);
  80. let callbacks = allCallbacks[eventName];
  81. if (!callbacks) {
  82. callbacks = allCallbacks[eventName] = [];
  83. }
  84. if (callbacks.indexOf(callback) === -1) {
  85. callbacks.push(callback);
  86. }
  87. },
  88. /**
  89. You can use `off` to stop firing a particular callback for an event:
  90. ```javascript
  91. function doStuff() { // do stuff! }
  92. object.on('stuff', doStuff);
  93. object.trigger('stuff'); // doStuff will be called
  94. // Unregister ONLY the doStuff callback
  95. object.off('stuff', doStuff);
  96. object.trigger('stuff'); // doStuff will NOT be called
  97. ```
  98. If you don't pass a `callback` argument to `off`, ALL callbacks for the
  99. event will not be executed when the event fires. For example:
  100. ```javascript
  101. let callback1 = function(){};
  102. let callback2 = function(){};
  103. object.on('stuff', callback1);
  104. object.on('stuff', callback2);
  105. object.trigger('stuff'); // callback1 and callback2 will be executed.
  106. object.off('stuff');
  107. object.trigger('stuff'); // callback1 and callback2 will not be executed!
  108. ```
  109. @method off
  110. @for rsvp
  111. @private
  112. @param {String} eventName event to stop listening to
  113. @param {Function} [callback] optional argument. If given, only the function
  114. given will be removed from the event's callback queue. If no `callback`
  115. argument is given, all callbacks will be removed from the event's callback
  116. queue.
  117. */
  118. off(eventName, callback) {
  119. let allCallbacks = callbacksFor(this);
  120. if (!callback) {
  121. allCallbacks[eventName] = [];
  122. return;
  123. }
  124. let callbacks = allCallbacks[eventName];
  125. let index = callbacks.indexOf(callback);
  126. if (index !== -1) {
  127. callbacks.splice(index, 1);
  128. }
  129. },
  130. /**
  131. Use `trigger` to fire custom events. For example:
  132. ```javascript
  133. object.on('foo', function(){
  134. console.log('foo event happened!');
  135. });
  136. object.trigger('foo');
  137. // 'foo event happened!' logged to the console
  138. ```
  139. You can also pass a value as a second argument to `trigger` that will be
  140. passed as an argument to all event listeners for the event:
  141. ```javascript
  142. object.on('foo', function(value){
  143. console.log(value.name);
  144. });
  145. object.trigger('foo', { name: 'bar' });
  146. // 'bar' logged to the console
  147. ```
  148. @method trigger
  149. @for rsvp
  150. @private
  151. @param {String} eventName name of the event to be triggered
  152. @param {*} [options] optional value to be passed to any event handlers for
  153. the given `eventName`
  154. */
  155. trigger(eventName, options, label) {
  156. let allCallbacks = callbacksFor(this);
  157. let callbacks = allCallbacks[eventName];
  158. if (callbacks) {
  159. // Don't cache the callbacks.length since it may grow
  160. let callback;
  161. for (let i = 0; i < callbacks.length; i++) {
  162. callback = callbacks[i];
  163. callback(options, label);
  164. }
  165. }
  166. }
  167. };
  168. const config = {
  169. instrument: false
  170. };
  171. EventTarget['mixin'](config);
  172. function configure(name, value) {
  173. if (arguments.length === 2) {
  174. config[name] = value;
  175. } else {
  176. return config[name];
  177. }
  178. }
  179. const queue = [];
  180. function scheduleFlush() {
  181. setTimeout(() => {
  182. for (let i = 0; i < queue.length; i++) {
  183. let entry = queue[i];
  184. let payload = entry.payload;
  185. payload.guid = payload.key + payload.id;
  186. payload.childGuid = payload.key + payload.childId;
  187. if (payload.error) {
  188. payload.stack = payload.error.stack;
  189. }
  190. config['trigger'](entry.name, entry.payload);
  191. }
  192. queue.length = 0;
  193. }, 50);
  194. }
  195. function instrument(eventName, promise, child) {
  196. if (1 === queue.push({
  197. name: eventName,
  198. payload: {
  199. key: promise._guidKey,
  200. id: promise._id,
  201. eventName: eventName,
  202. detail: promise._result,
  203. childId: child && child._id,
  204. label: promise._label,
  205. timeStamp: Date.now(),
  206. error: config["instrument-with-stack"] ? new Error(promise._label) : null
  207. }})) {
  208. scheduleFlush();
  209. }
  210. }
  211. /**
  212. `Promise.resolve` returns a promise that will become resolved with the
  213. passed `value`. It is shorthand for the following:
  214. ```javascript
  215. import Promise from 'rsvp';
  216. let promise = new Promise(function(resolve, reject){
  217. resolve(1);
  218. });
  219. promise.then(function(value){
  220. // value === 1
  221. });
  222. ```
  223. Instead of writing the above, your code now simply becomes the following:
  224. ```javascript
  225. import Promise from 'rsvp';
  226. let promise = RSVP.Promise.resolve(1);
  227. promise.then(function(value){
  228. // value === 1
  229. });
  230. ```
  231. @method resolve
  232. @for Promise
  233. @static
  234. @param {*} object value that the returned promise will be resolved with
  235. @param {String} [label] optional string for identifying the returned promise.
  236. Useful for tooling.
  237. @return {Promise} a promise that will become fulfilled with the given
  238. `value`
  239. */
  240. function resolve$$1(object, label) {
  241. /*jshint validthis:true */
  242. let Constructor = this;
  243. if (object && typeof object === 'object' && object.constructor === Constructor) {
  244. return object;
  245. }
  246. let promise = new Constructor(noop, label);
  247. resolve$1(promise, object);
  248. return promise;
  249. }
  250. function withOwnPromise() {
  251. return new TypeError('A promises callback cannot return that same promise.');
  252. }
  253. function objectOrFunction(x) {
  254. let type = typeof x;
  255. return x !== null && (type === 'object' || type === 'function');
  256. }
  257. function noop() {}
  258. const PENDING = void 0;
  259. const FULFILLED = 1;
  260. const REJECTED = 2;
  261. const TRY_CATCH_ERROR = { error: null };
  262. function getThen(promise) {
  263. try {
  264. return promise.then;
  265. } catch(error) {
  266. TRY_CATCH_ERROR.error = error;
  267. return TRY_CATCH_ERROR;
  268. }
  269. }
  270. let tryCatchCallback;
  271. function tryCatcher() {
  272. try {
  273. let target = tryCatchCallback;
  274. tryCatchCallback = null;
  275. return target.apply(this, arguments);
  276. } catch(e) {
  277. TRY_CATCH_ERROR.error = e;
  278. return TRY_CATCH_ERROR;
  279. }
  280. }
  281. function tryCatch(fn) {
  282. tryCatchCallback = fn;
  283. return tryCatcher;
  284. }
  285. function handleForeignThenable(promise, thenable, then$$1) {
  286. config.async(promise => {
  287. let sealed = false;
  288. let result = tryCatch(then$$1).call(
  289. thenable,
  290. value => {
  291. if (sealed) { return; }
  292. sealed = true;
  293. if (thenable === value) {
  294. fulfill(promise, value);
  295. } else {
  296. resolve$1(promise, value);
  297. }
  298. },
  299. reason => {
  300. if (sealed) { return; }
  301. sealed = true;
  302. reject(promise, reason);
  303. },
  304. 'Settle: ' + (promise._label || ' unknown promise')
  305. );
  306. if (!sealed && result === TRY_CATCH_ERROR) {
  307. sealed = true;
  308. let error = TRY_CATCH_ERROR.error;
  309. TRY_CATCH_ERROR.error = null;
  310. reject(promise, error);
  311. }
  312. }, promise);
  313. }
  314. function handleOwnThenable(promise, thenable) {
  315. if (thenable._state === FULFILLED) {
  316. fulfill(promise, thenable._result);
  317. } else if (thenable._state === REJECTED) {
  318. thenable._onError = null;
  319. reject(promise, thenable._result);
  320. } else {
  321. subscribe(thenable, undefined, value => {
  322. if (thenable === value) {
  323. fulfill(promise, value);
  324. } else {
  325. resolve$1(promise, value);
  326. }
  327. }, reason => reject(promise, reason));
  328. }
  329. }
  330. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  331. let isOwnThenable =
  332. maybeThenable.constructor === promise.constructor &&
  333. then$$1 === then &&
  334. promise.constructor.resolve === resolve$$1;
  335. if (isOwnThenable) {
  336. handleOwnThenable(promise, maybeThenable);
  337. } else if (then$$1 === TRY_CATCH_ERROR) {
  338. let error = TRY_CATCH_ERROR.error;
  339. TRY_CATCH_ERROR.error = null;
  340. reject(promise, error);
  341. } else if (typeof then$$1 === 'function') {
  342. handleForeignThenable(promise, maybeThenable, then$$1);
  343. } else {
  344. fulfill(promise, maybeThenable);
  345. }
  346. }
  347. function resolve$1(promise, value) {
  348. if (promise === value) {
  349. fulfill(promise, value);
  350. } else if (objectOrFunction(value)) {
  351. handleMaybeThenable(promise, value, getThen(value));
  352. } else {
  353. fulfill(promise, value);
  354. }
  355. }
  356. function publishRejection(promise) {
  357. if (promise._onError) {
  358. promise._onError(promise._result);
  359. }
  360. publish(promise);
  361. }
  362. function fulfill(promise, value) {
  363. if (promise._state !== PENDING) { return; }
  364. promise._result = value;
  365. promise._state = FULFILLED;
  366. if (promise._subscribers.length === 0) {
  367. if (config.instrument) {
  368. instrument('fulfilled', promise);
  369. }
  370. } else {
  371. config.async(publish, promise);
  372. }
  373. }
  374. function reject(promise, reason) {
  375. if (promise._state !== PENDING) { return; }
  376. promise._state = REJECTED;
  377. promise._result = reason;
  378. config.async(publishRejection, promise);
  379. }
  380. function subscribe(parent, child, onFulfillment, onRejection) {
  381. let subscribers = parent._subscribers;
  382. let length = subscribers.length;
  383. parent._onError = null;
  384. subscribers[length] = child;
  385. subscribers[length + FULFILLED] = onFulfillment;
  386. subscribers[length + REJECTED] = onRejection;
  387. if (length === 0 && parent._state) {
  388. config.async(publish, parent);
  389. }
  390. }
  391. function publish(promise) {
  392. let subscribers = promise._subscribers;
  393. let settled = promise._state;
  394. if (config.instrument) {
  395. instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);
  396. }
  397. if (subscribers.length === 0) { return; }
  398. let child, callback, result = promise._result;
  399. for (let i = 0; i < subscribers.length; i += 3) {
  400. child = subscribers[i];
  401. callback = subscribers[i + settled];
  402. if (child) {
  403. invokeCallback(settled, child, callback, result);
  404. } else {
  405. callback(result);
  406. }
  407. }
  408. promise._subscribers.length = 0;
  409. }
  410. function invokeCallback(state, promise, callback, result) {
  411. let hasCallback = typeof callback === 'function';
  412. let value;
  413. if (hasCallback) {
  414. value = tryCatch(callback)(result);
  415. } else {
  416. value = result;
  417. }
  418. if (promise._state !== PENDING) {
  419. // noop
  420. } else if (value === promise) {
  421. reject(promise, withOwnPromise());
  422. } else if (value === TRY_CATCH_ERROR) {
  423. let error = TRY_CATCH_ERROR.error;
  424. TRY_CATCH_ERROR.error = null; // release
  425. reject(promise, error);
  426. } else if (hasCallback) {
  427. resolve$1(promise, value);
  428. } else if (state === FULFILLED) {
  429. fulfill(promise, value);
  430. } else if (state === REJECTED) {
  431. reject(promise, value);
  432. }
  433. }
  434. function initializePromise(promise, resolver) {
  435. let resolved = false;
  436. try {
  437. resolver(value => {
  438. if (resolved) { return; }
  439. resolved = true;
  440. resolve$1(promise, value);
  441. }, reason => {
  442. if (resolved) { return; }
  443. resolved = true;
  444. reject(promise, reason);
  445. });
  446. } catch(e) {
  447. reject(promise, e);
  448. }
  449. }
  450. function then(onFulfillment, onRejection, label) {
  451. let parent = this;
  452. let state = parent._state;
  453. if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
  454. config.instrument && instrument('chained', parent, parent);
  455. return parent;
  456. }
  457. parent._onError = null;
  458. let child = new parent.constructor(noop, label);
  459. let result = parent._result;
  460. config.instrument && instrument('chained', parent, child);
  461. if (state === PENDING) {
  462. subscribe(parent, child, onFulfillment, onRejection);
  463. } else {
  464. let callback = state === FULFILLED ? onFulfillment : onRejection;
  465. config.async(() => invokeCallback(state, child, callback, result));
  466. }
  467. return child;
  468. }
  469. class Enumerator {
  470. constructor(Constructor, input, abortOnReject, label) {
  471. this._instanceConstructor = Constructor;
  472. this.promise = new Constructor(noop, label);
  473. this._abortOnReject = abortOnReject;
  474. this._isUsingOwnPromise = Constructor === Promise;
  475. this._isUsingOwnResolve = Constructor.resolve === resolve$$1;
  476. this._init(...arguments);
  477. }
  478. _init(Constructor, input) {
  479. let len = input.length || 0;
  480. this.length = len;
  481. this._remaining = len;
  482. this._result = new Array(len);
  483. this._enumerate(input);
  484. }
  485. _enumerate(input) {
  486. let length = this.length;
  487. let promise = this.promise;
  488. for (let i = 0; promise._state === PENDING && i < length; i++) {
  489. this._eachEntry(input[i], i, true);
  490. }
  491. this._checkFullfillment();
  492. }
  493. _checkFullfillment() {
  494. if (this._remaining === 0) {
  495. let result = this._result;
  496. fulfill(this.promise, result);
  497. this._result = null;
  498. }
  499. }
  500. _settleMaybeThenable(entry, i, firstPass) {
  501. let c = this._instanceConstructor;
  502. if (this._isUsingOwnResolve) {
  503. let then$$1 = getThen(entry);
  504. if (then$$1 === then && entry._state !== PENDING) {
  505. entry._onError = null;
  506. this._settledAt(entry._state, i, entry._result, firstPass);
  507. } else if (typeof then$$1 !== 'function') {
  508. this._settledAt(FULFILLED, i, entry, firstPass);
  509. } else if (this._isUsingOwnPromise) {
  510. let promise = new c(noop);
  511. handleMaybeThenable(promise, entry, then$$1);
  512. this._willSettleAt(promise, i, firstPass);
  513. } else {
  514. this._willSettleAt(new c(resolve => resolve(entry)), i, firstPass);
  515. }
  516. } else {
  517. this._willSettleAt(c.resolve(entry), i, firstPass);
  518. }
  519. }
  520. _eachEntry(entry, i, firstPass) {
  521. if (entry !== null && typeof entry === 'object') {
  522. this._settleMaybeThenable(entry, i, firstPass);
  523. } else {
  524. this._setResultAt(FULFILLED, i, entry, firstPass);
  525. }
  526. }
  527. _settledAt(state, i, value, firstPass) {
  528. let promise = this.promise;
  529. if (promise._state === PENDING) {
  530. if (this._abortOnReject && state === REJECTED) {
  531. reject(promise, value);
  532. } else {
  533. this._setResultAt(state, i, value, firstPass);
  534. this._checkFullfillment();
  535. }
  536. }
  537. }
  538. _setResultAt(state, i, value, firstPass) {
  539. this._remaining--;
  540. this._result[i] = value;
  541. }
  542. _willSettleAt(promise, i, firstPass) {
  543. subscribe(
  544. promise, undefined,
  545. value => this._settledAt(FULFILLED, i, value, firstPass),
  546. reason => this._settledAt(REJECTED, i, reason, firstPass)
  547. );
  548. }
  549. }
  550. function setSettledResult(state, i, value) {
  551. this._remaining--;
  552. if (state === FULFILLED) {
  553. this._result[i] = {
  554. state: 'fulfilled',
  555. value: value
  556. };
  557. } else {
  558. this._result[i] = {
  559. state: 'rejected',
  560. reason: value
  561. };
  562. }
  563. }
  564. /**
  565. `Promise.all` accepts an array of promises, and returns a new promise which
  566. is fulfilled with an array of fulfillment values for the passed promises, or
  567. rejected with the reason of the first passed promise to be rejected. It casts all
  568. elements of the passed iterable to promises as it runs this algorithm.
  569. Example:
  570. ```javascript
  571. import Promise, { resolve } from 'rsvp';
  572. let promise1 = resolve(1);
  573. let promise2 = resolve(2);
  574. let promise3 = resolve(3);
  575. let promises = [ promise1, promise2, promise3 ];
  576. Promise.all(promises).then(function(array){
  577. // The array here would be [ 1, 2, 3 ];
  578. });
  579. ```
  580. If any of the `promises` given to `RSVP.all` are rejected, the first promise
  581. that is rejected will be given as an argument to the returned promises's
  582. rejection handler. For example:
  583. Example:
  584. ```javascript
  585. import Promise, { resolve, reject } from 'rsvp';
  586. let promise1 = resolve(1);
  587. let promise2 = reject(new Error("2"));
  588. let promise3 = reject(new Error("3"));
  589. let promises = [ promise1, promise2, promise3 ];
  590. Promise.all(promises).then(function(array){
  591. // Code here never runs because there are rejected promises!
  592. }, function(error) {
  593. // error.message === "2"
  594. });
  595. ```
  596. @method all
  597. @for Promise
  598. @param {Array} entries array of promises
  599. @param {String} [label] optional string for labeling the promise.
  600. Useful for tooling.
  601. @return {Promise} promise that is fulfilled when all `promises` have been
  602. fulfilled, or rejected if any of them become rejected.
  603. @static
  604. */
  605. function all(entries, label) {
  606. if (!Array.isArray(entries)) {
  607. return this.reject(new TypeError("Promise.all must be called with an array"), label);
  608. }
  609. return new Enumerator(this, entries, true /* abort on reject */, label).promise;
  610. }
  611. /**
  612. `Promise.race` returns a new promise which is settled in the same way as the
  613. first passed promise to settle.
  614. Example:
  615. ```javascript
  616. import Promise from 'rsvp';
  617. let promise1 = new Promise(function(resolve, reject){
  618. setTimeout(function(){
  619. resolve('promise 1');
  620. }, 200);
  621. });
  622. let promise2 = new Promise(function(resolve, reject){
  623. setTimeout(function(){
  624. resolve('promise 2');
  625. }, 100);
  626. });
  627. Promise.race([promise1, promise2]).then(function(result){
  628. // result === 'promise 2' because it was resolved before promise1
  629. // was resolved.
  630. });
  631. ```
  632. `Promise.race` is deterministic in that only the state of the first
  633. settled promise matters. For example, even if other promises given to the
  634. `promises` array argument are resolved, but the first settled promise has
  635. become rejected before the other promises became fulfilled, the returned
  636. promise will become rejected:
  637. ```javascript
  638. import Promise from 'rsvp';
  639. let promise1 = new Promise(function(resolve, reject){
  640. setTimeout(function(){
  641. resolve('promise 1');
  642. }, 200);
  643. });
  644. let promise2 = new Promise(function(resolve, reject){
  645. setTimeout(function(){
  646. reject(new Error('promise 2'));
  647. }, 100);
  648. });
  649. Promise.race([promise1, promise2]).then(function(result){
  650. // Code here never runs
  651. }, function(reason){
  652. // reason.message === 'promise 2' because promise 2 became rejected before
  653. // promise 1 became fulfilled
  654. });
  655. ```
  656. An example real-world use case is implementing timeouts:
  657. ```javascript
  658. import Promise from 'rsvp';
  659. Promise.race([ajax('foo.json'), timeout(5000)])
  660. ```
  661. @method race
  662. @for Promise
  663. @static
  664. @param {Array} entries array of promises to observe
  665. @param {String} [label] optional string for describing the promise returned.
  666. Useful for tooling.
  667. @return {Promise} a promise which settles in the same way as the first passed
  668. promise to settle.
  669. */
  670. function race(entries, label) {
  671. /*jshint validthis:true */
  672. let Constructor = this;
  673. let promise = new Constructor(noop, label);
  674. if (!Array.isArray(entries)) {
  675. reject(promise, new TypeError('Promise.race must be called with an array'));
  676. return promise;
  677. }
  678. for (let i = 0; promise._state === PENDING && i < entries.length; i++) {
  679. subscribe(
  680. Constructor.resolve(entries[i]), undefined,
  681. value => resolve$1(promise, value),
  682. reason => reject(promise, reason)
  683. );
  684. }
  685. return promise;
  686. }
  687. /**
  688. `Promise.reject` returns a promise rejected with the passed `reason`.
  689. It is shorthand for the following:
  690. ```javascript
  691. import Promise from 'rsvp';
  692. let promise = new Promise(function(resolve, reject){
  693. reject(new Error('WHOOPS'));
  694. });
  695. promise.then(function(value){
  696. // Code here doesn't run because the promise is rejected!
  697. }, function(reason){
  698. // reason.message === 'WHOOPS'
  699. });
  700. ```
  701. Instead of writing the above, your code now simply becomes the following:
  702. ```javascript
  703. import Promise from 'rsvp';
  704. let promise = Promise.reject(new Error('WHOOPS'));
  705. promise.then(function(value){
  706. // Code here doesn't run because the promise is rejected!
  707. }, function(reason){
  708. // reason.message === 'WHOOPS'
  709. });
  710. ```
  711. @method reject
  712. @for Promise
  713. @static
  714. @param {*} reason value that the returned promise will be rejected with.
  715. @param {String} [label] optional string for identifying the returned promise.
  716. Useful for tooling.
  717. @return {Promise} a promise rejected with the given `reason`.
  718. */
  719. function reject$1(reason, label) {
  720. /*jshint validthis:true */
  721. let Constructor = this;
  722. let promise = new Constructor(noop, label);
  723. reject(promise, reason);
  724. return promise;
  725. }
  726. const guidKey = 'rsvp_' + Date.now() + '-';
  727. let counter = 0;
  728. function needsResolver() {
  729. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  730. }
  731. function needsNew() {
  732. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  733. }
  734. /**
  735. Promise objects represent the eventual result of an asynchronous operation. The
  736. primary way of interacting with a promise is through its `then` method, which
  737. registers callbacks to receive either a promise’s eventual value or the reason
  738. why the promise cannot be fulfilled.
  739. Terminology
  740. -----------
  741. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  742. - `thenable` is an object or function that defines a `then` method.
  743. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  744. - `exception` is a value that is thrown using the throw statement.
  745. - `reason` is a value that indicates why a promise was rejected.
  746. - `settled` the final resting state of a promise, fulfilled or rejected.
  747. A promise can be in one of three states: pending, fulfilled, or rejected.
  748. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  749. state. Promises that are rejected have a rejection reason and are in the
  750. rejected state. A fulfillment value is never a thenable.
  751. Promises can also be said to *resolve* a value. If this value is also a
  752. promise, then the original promise's settled state will match the value's
  753. settled state. So a promise that *resolves* a promise that rejects will
  754. itself reject, and a promise that *resolves* a promise that fulfills will
  755. itself fulfill.
  756. Basic Usage:
  757. ------------
  758. ```js
  759. let promise = new Promise(function(resolve, reject) {
  760. // on success
  761. resolve(value);
  762. // on failure
  763. reject(reason);
  764. });
  765. promise.then(function(value) {
  766. // on fulfillment
  767. }, function(reason) {
  768. // on rejection
  769. });
  770. ```
  771. Advanced Usage:
  772. ---------------
  773. Promises shine when abstracting away asynchronous interactions such as
  774. `XMLHttpRequest`s.
  775. ```js
  776. function getJSON(url) {
  777. return new Promise(function(resolve, reject){
  778. let xhr = new XMLHttpRequest();
  779. xhr.open('GET', url);
  780. xhr.onreadystatechange = handler;
  781. xhr.responseType = 'json';
  782. xhr.setRequestHeader('Accept', 'application/json');
  783. xhr.send();
  784. function handler() {
  785. if (this.readyState === this.DONE) {
  786. if (this.status === 200) {
  787. resolve(this.response);
  788. } else {
  789. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  790. }
  791. }
  792. };
  793. });
  794. }
  795. getJSON('/posts.json').then(function(json) {
  796. // on fulfillment
  797. }, function(reason) {
  798. // on rejection
  799. });
  800. ```
  801. Unlike callbacks, promises are great composable primitives.
  802. ```js
  803. Promise.all([
  804. getJSON('/posts'),
  805. getJSON('/comments')
  806. ]).then(function(values){
  807. values[0] // => postsJSON
  808. values[1] // => commentsJSON
  809. return values;
  810. });
  811. ```
  812. @class Promise
  813. @public
  814. @param {function} resolver
  815. @param {String} [label] optional string for labeling the promise.
  816. Useful for tooling.
  817. @constructor
  818. */
  819. class Promise {
  820. constructor(resolver, label) {
  821. this._id = counter++;
  822. this._label = label;
  823. this._state = undefined;
  824. this._result = undefined;
  825. this._subscribers = [];
  826. config.instrument && instrument('created', this);
  827. if (noop !== resolver) {
  828. typeof resolver !== 'function' && needsResolver();
  829. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  830. }
  831. }
  832. _onError(reason) {
  833. config.after(() => {
  834. if (this._onError) {
  835. config.trigger('error', reason, this._label);
  836. }
  837. });
  838. }
  839. /**
  840. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  841. as the catch block of a try/catch statement.
  842. ```js
  843. function findAuthor(){
  844. throw new Error('couldn\'t find that author');
  845. }
  846. // synchronous
  847. try {
  848. findAuthor();
  849. } catch(reason) {
  850. // something went wrong
  851. }
  852. // async with promises
  853. findAuthor().catch(function(reason){
  854. // something went wrong
  855. });
  856. ```
  857. @method catch
  858. @param {Function} onRejection
  859. @param {String} [label] optional string for labeling the promise.
  860. Useful for tooling.
  861. @return {Promise}
  862. */
  863. catch(onRejection, label) {
  864. return this.then(undefined, onRejection, label);
  865. }
  866. /**
  867. `finally` will be invoked regardless of the promise's fate just as native
  868. try/catch/finally behaves
  869. Synchronous example:
  870. ```js
  871. findAuthor() {
  872. if (Math.random() > 0.5) {
  873. throw new Error();
  874. }
  875. return new Author();
  876. }
  877. try {
  878. return findAuthor(); // succeed or fail
  879. } catch(error) {
  880. return findOtherAuthor();
  881. } finally {
  882. // always runs
  883. // doesn't affect the return value
  884. }
  885. ```
  886. Asynchronous example:
  887. ```js
  888. findAuthor().catch(function(reason){
  889. return findOtherAuthor();
  890. }).finally(function(){
  891. // author was either found, or not
  892. });
  893. ```
  894. @method finally
  895. @param {Function} callback
  896. @param {String} [label] optional string for labeling the promise.
  897. Useful for tooling.
  898. @return {Promise}
  899. */
  900. finally(callback, label) {
  901. let promise = this;
  902. let constructor = promise.constructor;
  903. if (typeof callback === 'function') {
  904. return promise.then(value => constructor.resolve(callback()).then(() => value),
  905. reason => constructor.resolve(callback()).then(() => { throw reason; }));
  906. }
  907. return promise.then(callback, callback);
  908. }
  909. }
  910. Promise.cast = resolve$$1; // deprecated
  911. Promise.all = all;
  912. Promise.race = race;
  913. Promise.resolve = resolve$$1;
  914. Promise.reject = reject$1;
  915. Promise.prototype._guidKey = guidKey;
  916. /**
  917. The primary way of interacting with a promise is through its `then` method,
  918. which registers callbacks to receive either a promise's eventual value or the
  919. reason why the promise cannot be fulfilled.
  920. ```js
  921. findUser().then(function(user){
  922. // user is available
  923. }, function(reason){
  924. // user is unavailable, and you are given the reason why
  925. });
  926. ```
  927. Chaining
  928. --------
  929. The return value of `then` is itself a promise. This second, 'downstream'
  930. promise is resolved with the return value of the first promise's fulfillment
  931. or rejection handler, or rejected if the handler throws an exception.
  932. ```js
  933. findUser().then(function (user) {
  934. return user.name;
  935. }, function (reason) {
  936. return 'default name';
  937. }).then(function (userName) {
  938. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  939. // will be `'default name'`
  940. });
  941. findUser().then(function (user) {
  942. throw new Error('Found user, but still unhappy');
  943. }, function (reason) {
  944. throw new Error('`findUser` rejected and we\'re unhappy');
  945. }).then(function (value) {
  946. // never reached
  947. }, function (reason) {
  948. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  949. // If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'.
  950. });
  951. ```
  952. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  953. ```js
  954. findUser().then(function (user) {
  955. throw new PedagogicalException('Upstream error');
  956. }).then(function (value) {
  957. // never reached
  958. }).then(function (value) {
  959. // never reached
  960. }, function (reason) {
  961. // The `PedgagocialException` is propagated all the way down to here
  962. });
  963. ```
  964. Assimilation
  965. ------------
  966. Sometimes the value you want to propagate to a downstream promise can only be
  967. retrieved asynchronously. This can be achieved by returning a promise in the
  968. fulfillment or rejection handler. The downstream promise will then be pending
  969. until the returned promise is settled. This is called *assimilation*.
  970. ```js
  971. findUser().then(function (user) {
  972. return findCommentsByAuthor(user);
  973. }).then(function (comments) {
  974. // The user's comments are now available
  975. });
  976. ```
  977. If the assimliated promise rejects, then the downstream promise will also reject.
  978. ```js
  979. findUser().then(function (user) {
  980. return findCommentsByAuthor(user);
  981. }).then(function (comments) {
  982. // If `findCommentsByAuthor` fulfills, we'll have the value here
  983. }, function (reason) {
  984. // If `findCommentsByAuthor` rejects, we'll have the reason here
  985. });
  986. ```
  987. Simple Example
  988. --------------
  989. Synchronous Example
  990. ```javascript
  991. let result;
  992. try {
  993. result = findResult();
  994. // success
  995. } catch(reason) {
  996. // failure
  997. }
  998. ```
  999. Errback Example
  1000. ```js
  1001. findResult(function(result, err){
  1002. if (err) {
  1003. // failure
  1004. } else {
  1005. // success
  1006. }
  1007. });
  1008. ```
  1009. Promise Example;
  1010. ```javascript
  1011. findResult().then(function(result){
  1012. // success
  1013. }, function(reason){
  1014. // failure
  1015. });
  1016. ```
  1017. Advanced Example
  1018. --------------
  1019. Synchronous Example
  1020. ```javascript
  1021. let author, books;
  1022. try {
  1023. author = findAuthor();
  1024. books = findBooksByAuthor(author);
  1025. // success
  1026. } catch(reason) {
  1027. // failure
  1028. }
  1029. ```
  1030. Errback Example
  1031. ```js
  1032. function foundBooks(books) {
  1033. }
  1034. function failure(reason) {
  1035. }
  1036. findAuthor(function(author, err){
  1037. if (err) {
  1038. failure(err);
  1039. // failure
  1040. } else {
  1041. try {
  1042. findBoooksByAuthor(author, function(books, err) {
  1043. if (err) {
  1044. failure(err);
  1045. } else {
  1046. try {
  1047. foundBooks(books);
  1048. } catch(reason) {
  1049. failure(reason);
  1050. }
  1051. }
  1052. });
  1053. } catch(error) {
  1054. failure(err);
  1055. }
  1056. // success
  1057. }
  1058. });
  1059. ```
  1060. Promise Example;
  1061. ```javascript
  1062. findAuthor().
  1063. then(findBooksByAuthor).
  1064. then(function(books){
  1065. // found books
  1066. }).catch(function(reason){
  1067. // something went wrong
  1068. });
  1069. ```
  1070. @method then
  1071. @param {Function} onFulfillment
  1072. @param {Function} onRejection
  1073. @param {String} [label] optional string for labeling the promise.
  1074. Useful for tooling.
  1075. @return {Promise}
  1076. */
  1077. Promise.prototype.then = then;
  1078. function makeObject(_, argumentNames) {
  1079. let obj = {};
  1080. let length = _.length;
  1081. let args = new Array(length);
  1082. for (let x = 0; x < length; x++) {
  1083. args[x] = _[x];
  1084. }
  1085. for (let i = 0; i < argumentNames.length; i++) {
  1086. let name = argumentNames[i];
  1087. obj[name] = args[i + 1];
  1088. }
  1089. return obj;
  1090. }
  1091. function arrayResult(_) {
  1092. let length = _.length;
  1093. let args = new Array(length - 1);
  1094. for (let i = 1; i < length; i++) {
  1095. args[i - 1] = _[i];
  1096. }
  1097. return args;
  1098. }
  1099. function wrapThenable(then, promise) {
  1100. return {
  1101. then(onFulFillment, onRejection) {
  1102. return then.call(promise, onFulFillment, onRejection);
  1103. }
  1104. };
  1105. }
  1106. /**
  1107. `denodeify` takes a 'node-style' function and returns a function that
  1108. will return an `Promise`. You can use `denodeify` in Node.js or the
  1109. browser when you'd prefer to use promises over using callbacks. For example,
  1110. `denodeify` transforms the following:
  1111. ```javascript
  1112. let fs = require('fs');
  1113. fs.readFile('myfile.txt', function(err, data){
  1114. if (err) return handleError(err);
  1115. handleData(data);
  1116. });
  1117. ```
  1118. into:
  1119. ```javascript
  1120. let fs = require('fs');
  1121. let readFile = denodeify(fs.readFile);
  1122. readFile('myfile.txt').then(handleData, handleError);
  1123. ```
  1124. If the node function has multiple success parameters, then `denodeify`
  1125. just returns the first one:
  1126. ```javascript
  1127. let request = denodeify(require('request'));
  1128. request('http://example.com').then(function(res) {
  1129. // ...
  1130. });
  1131. ```
  1132. However, if you need all success parameters, setting `denodeify`'s
  1133. second parameter to `true` causes it to return all success parameters
  1134. as an array:
  1135. ```javascript
  1136. let request = denodeify(require('request'), true);
  1137. request('http://example.com').then(function(result) {
  1138. // result[0] -> res
  1139. // result[1] -> body
  1140. });
  1141. ```
  1142. Or if you pass it an array with names it returns the parameters as a hash:
  1143. ```javascript
  1144. let request = denodeify(require('request'), ['res', 'body']);
  1145. request('http://example.com').then(function(result) {
  1146. // result.res
  1147. // result.body
  1148. });
  1149. ```
  1150. Sometimes you need to retain the `this`:
  1151. ```javascript
  1152. let app = require('express')();
  1153. let render = denodeify(app.render.bind(app));
  1154. ```
  1155. The denodified function inherits from the original function. It works in all
  1156. environments, except IE 10 and below. Consequently all properties of the original
  1157. function are available to you. However, any properties you change on the
  1158. denodeified function won't be changed on the original function. Example:
  1159. ```javascript
  1160. let request = denodeify(require('request')),
  1161. cookieJar = request.jar(); // <- Inheritance is used here
  1162. request('http://example.com', {jar: cookieJar}).then(function(res) {
  1163. // cookieJar.cookies holds now the cookies returned by example.com
  1164. });
  1165. ```
  1166. Using `denodeify` makes it easier to compose asynchronous operations instead
  1167. of using callbacks. For example, instead of:
  1168. ```javascript
  1169. let fs = require('fs');
  1170. fs.readFile('myfile.txt', function(err, data){
  1171. if (err) { ... } // Handle error
  1172. fs.writeFile('myfile2.txt', data, function(err){
  1173. if (err) { ... } // Handle error
  1174. console.log('done')
  1175. });
  1176. });
  1177. ```
  1178. you can chain the operations together using `then` from the returned promise:
  1179. ```javascript
  1180. let fs = require('fs');
  1181. let readFile = denodeify(fs.readFile);
  1182. let writeFile = denodeify(fs.writeFile);
  1183. readFile('myfile.txt').then(function(data){
  1184. return writeFile('myfile2.txt', data);
  1185. }).then(function(){
  1186. console.log('done')
  1187. }).catch(function(error){
  1188. // Handle error
  1189. });
  1190. ```
  1191. @method denodeify
  1192. @public
  1193. @static
  1194. @for rsvp
  1195. @param {Function} nodeFunc a 'node-style' function that takes a callback as
  1196. its last argument. The callback expects an error to be passed as its first
  1197. argument (if an error occurred, otherwise null), and the value from the
  1198. operation as its second argument ('function(err, value){ }').
  1199. @param {Boolean|Array} [options] An optional paramter that if set
  1200. to `true` causes the promise to fulfill with the callback's success arguments
  1201. as an array. This is useful if the node function has multiple success
  1202. paramters. If you set this paramter to an array with names, the promise will
  1203. fulfill with a hash with these names as keys and the success parameters as
  1204. values.
  1205. @return {Function} a function that wraps `nodeFunc` to return a `Promise`
  1206. */
  1207. function denodeify(nodeFunc, options) {
  1208. let fn = function() {
  1209. let l = arguments.length;
  1210. let args = new Array(l + 1);
  1211. let promiseInput = false;
  1212. for (let i = 0; i < l; ++i) {
  1213. let arg = arguments[i];
  1214. if (!promiseInput) {
  1215. // TODO: clean this up
  1216. promiseInput = needsPromiseInput(arg);
  1217. if (promiseInput === TRY_CATCH_ERROR) {
  1218. let error = TRY_CATCH_ERROR.error;
  1219. TRY_CATCH_ERROR.error = null;
  1220. let p = new Promise(noop);
  1221. reject(p, error);
  1222. return p;
  1223. } else if (promiseInput && promiseInput !== true) {
  1224. arg = wrapThenable(promiseInput, arg);
  1225. }
  1226. }
  1227. args[i] = arg;
  1228. }
  1229. let promise = new Promise(noop);
  1230. args[l] = function(err, val) {
  1231. if (err) {
  1232. reject(promise, err);
  1233. } else if (options === undefined) {
  1234. resolve$1(promise, val);
  1235. } else if (options === true) {
  1236. resolve$1(promise, arrayResult(arguments));
  1237. } else if (Array.isArray(options)) {
  1238. resolve$1(promise, makeObject(arguments, options));
  1239. } else {
  1240. resolve$1(promise, val);
  1241. }
  1242. };
  1243. if (promiseInput) {
  1244. return handlePromiseInput(promise, args, nodeFunc, this);
  1245. } else {
  1246. return handleValueInput(promise, args, nodeFunc, this);
  1247. }
  1248. };
  1249. fn.__proto__ = nodeFunc;
  1250. return fn;
  1251. }
  1252. function handleValueInput(promise, args, nodeFunc, self) {
  1253. let result = tryCatch(nodeFunc).apply(self, args);
  1254. if (result === TRY_CATCH_ERROR) {
  1255. let error = TRY_CATCH_ERROR.error;
  1256. TRY_CATCH_ERROR.error = null;
  1257. reject(promise, error);
  1258. }
  1259. return promise;
  1260. }
  1261. function handlePromiseInput(promise, args, nodeFunc, self){
  1262. return Promise.all(args)
  1263. .then(args => handleValueInput(promise, args, nodeFunc, self));
  1264. }
  1265. function needsPromiseInput(arg) {
  1266. if (arg !== null && typeof arg === 'object') {
  1267. if (arg.constructor === Promise) {
  1268. return true;
  1269. } else {
  1270. return getThen(arg);
  1271. }
  1272. } else {
  1273. return false;
  1274. }
  1275. }
  1276. /**
  1277. This is a convenient alias for `Promise.all`.
  1278. @method all
  1279. @public
  1280. @static
  1281. @for rsvp
  1282. @param {Array} array Array of promises.
  1283. @param {String} [label] An optional label. This is useful
  1284. for tooling.
  1285. */
  1286. function all$1(array, label) {
  1287. return Promise.all(array, label);
  1288. }
  1289. /**
  1290. @module rsvp
  1291. @public
  1292. **/
  1293. class AllSettled extends Enumerator {
  1294. constructor(Constructor, entries, label) {
  1295. super(Constructor, entries, false /* don't abort on reject */, label);
  1296. }
  1297. }
  1298. AllSettled.prototype._setResultAt = setSettledResult;
  1299. /**
  1300. `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing
  1301. a fail-fast method, it waits until all the promises have returned and
  1302. shows you all the results. This is useful if you want to handle multiple
  1303. promises' failure states together as a set.
  1304. Returns a promise that is fulfilled when all the given promises have been
  1305. settled. The return promise is fulfilled with an array of the states of
  1306. the promises passed into the `promises` array argument.
  1307. Each state object will either indicate fulfillment or rejection, and
  1308. provide the corresponding value or reason. The states will take one of
  1309. the following formats:
  1310. ```javascript
  1311. { state: 'fulfilled', value: value }
  1312. or
  1313. { state: 'rejected', reason: reason }
  1314. ```
  1315. Example:
  1316. ```javascript
  1317. let promise1 = RSVP.Promise.resolve(1);
  1318. let promise2 = RSVP.Promise.reject(new Error('2'));
  1319. let promise3 = RSVP.Promise.reject(new Error('3'));
  1320. let promises = [ promise1, promise2, promise3 ];
  1321. RSVP.allSettled(promises).then(function(array){
  1322. // array == [
  1323. // { state: 'fulfilled', value: 1 },
  1324. // { state: 'rejected', reason: Error },
  1325. // { state: 'rejected', reason: Error }
  1326. // ]
  1327. // Note that for the second item, reason.message will be '2', and for the
  1328. // third item, reason.message will be '3'.
  1329. }, function(error) {
  1330. // Not run. (This block would only be called if allSettled had failed,
  1331. // for instance if passed an incorrect argument type.)
  1332. });
  1333. ```
  1334. @method allSettled
  1335. @public
  1336. @static
  1337. @for rsvp
  1338. @param {Array} entries
  1339. @param {String} [label] - optional string that describes the promise.
  1340. Useful for tooling.
  1341. @return {Promise} promise that is fulfilled with an array of the settled
  1342. states of the constituent promises.
  1343. */
  1344. function allSettled(entries, label) {
  1345. if (!Array.isArray(entries)) {
  1346. return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label);
  1347. }
  1348. return new AllSettled(Promise, entries, label).promise;
  1349. }
  1350. /**
  1351. This is a convenient alias for `Promise.race`.
  1352. @method race
  1353. @public
  1354. @static
  1355. @for rsvp
  1356. @param {Array} array Array of promises.
  1357. @param {String} [label] An optional label. This is useful
  1358. for tooling.
  1359. */
  1360. function race$1(array, label) {
  1361. return Promise.race(array, label);
  1362. }
  1363. class PromiseHash extends Enumerator {
  1364. constructor(Constructor, object, abortOnReject = true, label) {
  1365. super(Constructor, object, abortOnReject, label);
  1366. }
  1367. _init(Constructor, object) {
  1368. this._result = {};
  1369. this._enumerate(object);
  1370. }
  1371. _enumerate(input) {
  1372. let keys = Object.keys(input);
  1373. let length = keys.length;
  1374. let promise = this.promise;
  1375. this._remaining = length;
  1376. let key, val;
  1377. for (let i = 0; promise._state === PENDING && i < length; i++) {
  1378. key = keys[i];
  1379. val = input[key];
  1380. this._eachEntry(val, key, true);
  1381. }
  1382. this._checkFullfillment();
  1383. }
  1384. }
  1385. /**
  1386. `hash` is similar to `all`, but takes an object instead of an array
  1387. for its `promises` argument.
  1388. Returns a promise that is fulfilled when all the given promises have been
  1389. fulfilled, or rejected if any of them become rejected. The returned promise
  1390. is fulfilled with a hash that has the same key names as the `promises` object
  1391. argument. If any of the values in the object are not promises, they will
  1392. simply be copied over to the fulfilled object.
  1393. Example:
  1394. ```javascript
  1395. let promises = {
  1396. myPromise: resolve(1),
  1397. yourPromise: resolve(2),
  1398. theirPromise: resolve(3),
  1399. notAPromise: 4
  1400. };
  1401. hash(promises).then(function(hash){
  1402. // hash here is an object that looks like:
  1403. // {
  1404. // myPromise: 1,
  1405. // yourPromise: 2,
  1406. // theirPromise: 3,
  1407. // notAPromise: 4
  1408. // }
  1409. });
  1410. ```
  1411. If any of the `promises` given to `hash` are rejected, the first promise
  1412. that is rejected will be given as the reason to the rejection handler.
  1413. Example:
  1414. ```javascript
  1415. let promises = {
  1416. myPromise: resolve(1),
  1417. rejectedPromise: reject(new Error('rejectedPromise')),
  1418. anotherRejectedPromise: reject(new Error('anotherRejectedPromise')),
  1419. };
  1420. hash(promises).then(function(hash){
  1421. // Code here never runs because there are rejected promises!
  1422. }, function(reason) {
  1423. // reason.message === 'rejectedPromise'
  1424. });
  1425. ```
  1426. An important note: `hash` is intended for plain JavaScript objects that
  1427. are just a set of keys and values. `hash` will NOT preserve prototype
  1428. chains.
  1429. Example:
  1430. ```javascript
  1431. import { hash, resolve } from 'rsvp';
  1432. function MyConstructor(){
  1433. this.example = resolve('Example');
  1434. }
  1435. MyConstructor.prototype = {
  1436. protoProperty: resolve('Proto Property')
  1437. };
  1438. let myObject = new MyConstructor();
  1439. hash(myObject).then(function(hash){
  1440. // protoProperty will not be present, instead you will just have an
  1441. // object that looks like:
  1442. // {
  1443. // example: 'Example'
  1444. // }
  1445. //
  1446. // hash.hasOwnProperty('protoProperty'); // false
  1447. // 'undefined' === typeof hash.protoProperty
  1448. });
  1449. ```
  1450. @method hash
  1451. @public
  1452. @static
  1453. @for rsvp
  1454. @param {Object} object
  1455. @param {String} [label] optional string that describes the promise.
  1456. Useful for tooling.
  1457. @return {Promise} promise that is fulfilled when all properties of `promises`
  1458. have been fulfilled, or rejected if any of them become rejected.
  1459. */
  1460. function hash(object, label) {
  1461. return Promise.resolve(object, label)
  1462. .then(function(object) {
  1463. if (object === null || typeof object !== 'object') {
  1464. throw new TypeError("Promise.hash must be called with an object");
  1465. }
  1466. return new PromiseHash(Promise, object, label).promise;
  1467. });
  1468. }
  1469. class HashSettled extends PromiseHash {
  1470. constructor(Constructor, object, label) {
  1471. super(Constructor, object, false, label);
  1472. }
  1473. }
  1474. HashSettled.prototype._setResultAt = setSettledResult;
  1475. /**
  1476. `hashSettled` is similar to `allSettled`, but takes an object
  1477. instead of an array for its `promises` argument.
  1478. Unlike `all` or `hash`, which implement a fail-fast method,
  1479. but like `allSettled`, `hashSettled` waits until all the
  1480. constituent promises have returned and then shows you all the results
  1481. with their states and values/reasons. This is useful if you want to
  1482. handle multiple promises' failure states together as a set.
  1483. Returns a promise that is fulfilled when all the given promises have been
  1484. settled, or rejected if the passed parameters are invalid.
  1485. The returned promise is fulfilled with a hash that has the same key names as
  1486. the `promises` object argument. If any of the values in the object are not
  1487. promises, they will be copied over to the fulfilled object and marked with state
  1488. 'fulfilled'.
  1489. Example:
  1490. ```javascript
  1491. import { hashSettled, resolve } from 'rsvp';
  1492. let promises = {
  1493. myPromise: resolve(1),
  1494. yourPromise: resolve(2),
  1495. theirPromise: resolve(3),
  1496. notAPromise: 4
  1497. };
  1498. hashSettled(promises).then(function(hash){
  1499. // hash here is an object that looks like:
  1500. // {
  1501. // myPromise: { state: 'fulfilled', value: 1 },
  1502. // yourPromise: { state: 'fulfilled', value: 2 },
  1503. // theirPromise: { state: 'fulfilled', value: 3 },
  1504. // notAPromise: { state: 'fulfilled', value: 4 }
  1505. // }
  1506. });
  1507. ```
  1508. If any of the `promises` given to `hash` are rejected, the state will
  1509. be set to 'rejected' and the reason for rejection provided.
  1510. Example:
  1511. ```javascript
  1512. import { hashSettled, reject, resolve } from 'rsvp';
  1513. let promises = {
  1514. myPromise: resolve(1),
  1515. rejectedPromise: reject(new Error('rejection')),
  1516. anotherRejectedPromise: reject(new Error('more rejection')),
  1517. };
  1518. hashSettled(promises).then(function(hash){
  1519. // hash here is an object that looks like:
  1520. // {
  1521. // myPromise: { state: 'fulfilled', value: 1 },
  1522. // rejectedPromise: { state: 'rejected', reason: Error },
  1523. // anotherRejectedPromise: { state: 'rejected', reason: Error },
  1524. // }
  1525. // Note that for rejectedPromise, reason.message == 'rejection',
  1526. // and for anotherRejectedPromise, reason.message == 'more rejection'.
  1527. });
  1528. ```
  1529. An important note: `hashSettled` is intended for plain JavaScript objects that
  1530. are just a set of keys and values. `hashSettled` will NOT preserve prototype
  1531. chains.
  1532. Example:
  1533. ```javascript
  1534. import Promise, { hashSettled, resolve } from 'rsvp';
  1535. function MyConstructor(){
  1536. this.example = resolve('Example');
  1537. }
  1538. MyConstructor.prototype = {
  1539. protoProperty: Promise.resolve('Proto Property')
  1540. };
  1541. let myObject = new MyConstructor();
  1542. hashSettled(myObject).then(function(hash){
  1543. // protoProperty will not be present, instead you will just have an
  1544. // object that looks like:
  1545. // {
  1546. // example: { state: 'fulfilled', value: 'Example' }
  1547. // }
  1548. //
  1549. // hash.hasOwnProperty('protoProperty'); // false
  1550. // 'undefined' === typeof hash.protoProperty
  1551. });
  1552. ```
  1553. @method hashSettled
  1554. @public
  1555. @for rsvp
  1556. @param {Object} object
  1557. @param {String} [label] optional string that describes the promise.
  1558. Useful for tooling.
  1559. @return {Promise} promise that is fulfilled when when all properties of `promises`
  1560. have been settled.
  1561. @static
  1562. */
  1563. function hashSettled(object, label) {
  1564. return Promise.resolve(object, label)
  1565. .then(function(object) {
  1566. if (object === null || typeof object !== 'object') {
  1567. throw new TypeError("hashSettled must be called with an object");
  1568. }
  1569. return new HashSettled(Promise, object, false, label).promise;
  1570. });
  1571. }
  1572. /**
  1573. `rethrow` will rethrow an error on the next turn of the JavaScript event
  1574. loop in order to aid debugging.
  1575. Promises A+ specifies that any exceptions that occur with a promise must be
  1576. caught by the promises implementation and bubbled to the last handler. For
  1577. this reason, it is recommended that you always specify a second rejection
  1578. handler function to `then`. However, `rethrow` will throw the exception
  1579. outside of the promise, so it bubbles up to your console if in the browser,
  1580. or domain/cause uncaught exception in Node. `rethrow` will also throw the
  1581. error again so the error can be handled by the promise per the spec.
  1582. ```javascript
  1583. import { rethrow } from 'rsvp';
  1584. function throws(){
  1585. throw new Error('Whoops!');
  1586. }
  1587. let promise = new Promise(function(resolve, reject){
  1588. throws();
  1589. });
  1590. promise.catch(rethrow).then(function(){
  1591. // Code here doesn't run because the promise became rejected due to an
  1592. // error!
  1593. }, function (err){
  1594. // handle the error here
  1595. });
  1596. ```
  1597. The 'Whoops' error will be thrown on the next turn of the event loop
  1598. and you can watch for it in your console. You can also handle it using a
  1599. rejection handler given to `.then` or `.catch` on the returned promise.
  1600. @method rethrow
  1601. @public
  1602. @static
  1603. @for rsvp
  1604. @param {Error} reason reason the promise became rejected.
  1605. @throws Error
  1606. @static
  1607. */
  1608. function rethrow(reason) {
  1609. setTimeout(() => {
  1610. throw reason;
  1611. });
  1612. throw reason;
  1613. }
  1614. /**
  1615. `defer` returns an object similar to jQuery's `$.Deferred`.
  1616. `defer` should be used when porting over code reliant on `$.Deferred`'s
  1617. interface. New code should use the `Promise` constructor instead.
  1618. The object returned from `defer` is a plain object with three properties:
  1619. * promise - an `Promise`.
  1620. * reject - a function that causes the `promise` property on this object to
  1621. become rejected
  1622. * resolve - a function that causes the `promise` property on this object to
  1623. become fulfilled.
  1624. Example:
  1625. ```javascript
  1626. let deferred = defer();
  1627. deferred.resolve("Success!");
  1628. deferred.promise.then(function(value){
  1629. // value here is "Success!"
  1630. });
  1631. ```
  1632. @method defer
  1633. @public
  1634. @static
  1635. @for rsvp
  1636. @param {String} [label] optional string for labeling the promise.
  1637. Useful for tooling.
  1638. @return {Object}
  1639. */
  1640. function defer(label) {
  1641. let deferred = { resolve: undefined, reject: undefined };
  1642. deferred.promise = new Promise((resolve, reject) => {
  1643. deferred.resolve = resolve;
  1644. deferred.reject = reject;
  1645. }, label);
  1646. return deferred;
  1647. }
  1648. class MapEnumerator extends Enumerator {
  1649. constructor(Constructor, entries, mapFn, label) {
  1650. super(Constructor, entries, true, label, mapFn);
  1651. }
  1652. _init(Constructor, input, bool, label, mapFn) {
  1653. let len = input.length || 0;
  1654. this.length = len;
  1655. this._remaining = len;
  1656. this._result = new Array(len);
  1657. this._mapFn = mapFn;
  1658. this._enumerate(input);
  1659. }
  1660. _setResultAt(state, i, value, firstPass) {
  1661. if (firstPass) {
  1662. let val = tryCatch(this._mapFn)(value, i);
  1663. if (val === TRY_CATCH_ERROR) {
  1664. this._settledAt(REJECTED, i, val.error, false);
  1665. } else {
  1666. this._eachEntry(val, i, false);
  1667. }
  1668. } else {
  1669. this._remaining--;
  1670. this._result[i] = value;
  1671. }
  1672. }
  1673. }
  1674. /**
  1675. `map` is similar to JavaScript's native `map` method. `mapFn` is eagerly called
  1676. meaning that as soon as any promise resolves its value will be passed to `mapFn`.
  1677. `map` returns a promise that will become fulfilled with the result of running
  1678. `mapFn` on the values the promises become fulfilled with.
  1679. For example:
  1680. ```javascript
  1681. import { map, resolve } from 'rsvp';
  1682. let promise1 = resolve(1);
  1683. let promise2 = resolve(2);
  1684. let promise3 = resolve(3);
  1685. let promises = [ promise1, promise2, promise3 ];
  1686. let mapFn = function(item){
  1687. return item + 1;
  1688. };
  1689. map(promises, mapFn).then(function(result){
  1690. // result is [ 2, 3, 4 ]
  1691. });
  1692. ```
  1693. If any of the `promises` given to `map` are rejected, the first promise
  1694. that is rejected will be given as an argument to the returned promise's
  1695. rejection handler. For example:
  1696. ```javascript
  1697. import { map, reject, resolve } from 'rsvp';
  1698. let promise1 = resolve(1);
  1699. let promise2 = reject(new Error('2'));
  1700. let promise3 = reject(new Error('3'));
  1701. let promises = [ promise1, promise2, promise3 ];
  1702. let mapFn = function(item){
  1703. return item + 1;
  1704. };
  1705. map(promises, mapFn).then(function(array){
  1706. // Code here never runs because there are rejected promises!
  1707. }, function(reason) {
  1708. // reason.message === '2'
  1709. });
  1710. ```
  1711. `map` will also wait if a promise is returned from `mapFn`. For example,
  1712. say you want to get all comments from a set of blog posts, but you need
  1713. the blog posts first because they contain a url to those comments.
  1714. ```javscript
  1715. import { map } from 'rsvp';
  1716. let mapFn = function(blogPost){
  1717. // getComments does some ajax and returns an Promise that is fulfilled
  1718. // with some comments data
  1719. return getComments(blogPost.comments_url);
  1720. };
  1721. // getBlogPosts does some ajax and returns an Promise that is fulfilled
  1722. // with some blog post data
  1723. map(getBlogPosts(), mapFn).then(function(comments){
  1724. // comments is the result of asking the server for the comments
  1725. // of all blog posts returned from getBlogPosts()
  1726. });
  1727. ```
  1728. @method map
  1729. @public
  1730. @static
  1731. @for rsvp
  1732. @param {Array} promises
  1733. @param {Function} mapFn function to be called on each fulfilled promise.
  1734. @param {String} [label] optional string for labeling the promise.
  1735. Useful for tooling.
  1736. @return {Promise} promise that is fulfilled with the result of calling
  1737. `mapFn` on each fulfilled promise or value when they become fulfilled.
  1738. The promise will be rejected if any of the given `promises` become rejected.
  1739. */
  1740. function map(promises, mapFn, label) {
  1741. if (typeof mapFn !== 'function') {
  1742. return Promise.reject(new TypeError("map expects a function as a second argument"), label);
  1743. }
  1744. return Promise.resolve(promises, label)
  1745. .then(function(promises) {
  1746. if (!Array.isArray(promises)) {
  1747. throw new TypeError("map must be called with an array");
  1748. }
  1749. return new MapEnumerator(Promise, promises, mapFn, label).promise;
  1750. });
  1751. }
  1752. /**
  1753. This is a convenient alias for `Promise.resolve`.
  1754. @method resolve
  1755. @public
  1756. @static
  1757. @for rsvp
  1758. @param {*} value value that the returned promise will be resolved with
  1759. @param {String} [label] optional string for identifying the returned promise.
  1760. Useful for tooling.
  1761. @return {Promise} a promise that will become fulfilled with the given
  1762. `value`
  1763. */
  1764. function resolve$2(value, label) {
  1765. return Promise.resolve(value, label);
  1766. }
  1767. /**
  1768. This is a convenient alias for `Promise.reject`.
  1769. @method reject
  1770. @public
  1771. @static
  1772. @for rsvp
  1773. @param {*} reason value that the returned promise will be rejected with.
  1774. @param {String} [label] optional string for identifying the returned promise.
  1775. Useful for tooling.
  1776. @return {Promise} a promise rejected with the given `reason`.
  1777. */
  1778. function reject$2(reason, label) {
  1779. return Promise.reject(reason, label);
  1780. }
  1781. const EMPTY_OBJECT = {};
  1782. class FilterEnumerator extends MapEnumerator {
  1783. _checkFullfillment() {
  1784. if (this._remaining === 0 && this._result !== null) {
  1785. let result = this._result.filter((val) => val !== EMPTY_OBJECT);
  1786. fulfill(this.promise, result);
  1787. this._result = null;
  1788. }
  1789. }
  1790. _setResultAt(state, i, value, firstPass) {
  1791. if (firstPass) {
  1792. this._result[i] = value;
  1793. let val = tryCatch(this._mapFn)(value, i);
  1794. if (val === TRY_CATCH_ERROR) {
  1795. this._settledAt(REJECTED, i, val.error, false);
  1796. } else {
  1797. this._eachEntry(val, i, false);
  1798. }
  1799. } else {
  1800. this._remaining--;
  1801. if (!value) {
  1802. this._result[i] = EMPTY_OBJECT;
  1803. }
  1804. }
  1805. }
  1806. }
  1807. /**
  1808. `filter` is similar to JavaScript's native `filter` method.
  1809. `filterFn` is eagerly called meaning that as soon as any promise
  1810. resolves its value will be passed to `filterFn`. `filter` returns
  1811. a promise that will become fulfilled with the result of running
  1812. `filterFn` on the values the promises become fulfilled with.
  1813. For example:
  1814. ```javascript
  1815. import { filter, resolve } from 'rsvp';
  1816. let promise1 = resolve(1);
  1817. let promise2 = resolve(2);
  1818. let promise3 = resolve(3);
  1819. let promises = [promise1, promise2, promise3];
  1820. let filterFn = function(item){
  1821. return item > 1;
  1822. };
  1823. filter(promises, filterFn).then(function(result){
  1824. // result is [ 2, 3 ]
  1825. });
  1826. ```
  1827. If any of the `promises` given to `filter` are rejected, the first promise
  1828. that is rejected will be given as an argument to the returned promise's
  1829. rejection handler. For example:
  1830. ```javascript
  1831. import { filter, reject, resolve } from 'rsvp';
  1832. let promise1 = resolve(1);
  1833. let promise2 = reject(new Error('2'));
  1834. let promise3 = reject(new Error('3'));
  1835. let promises = [ promise1, promise2, promise3 ];
  1836. let filterFn = function(item){
  1837. return item > 1;
  1838. };
  1839. filter(promises, filterFn).then(function(array){
  1840. // Code here never runs because there are rejected promises!
  1841. }, function(reason) {
  1842. // reason.message === '2'
  1843. });
  1844. ```
  1845. `filter` will also wait for any promises returned from `filterFn`.
  1846. For instance, you may want to fetch a list of users then return a subset
  1847. of those users based on some asynchronous operation:
  1848. ```javascript
  1849. import { filter, resolve } from 'rsvp';
  1850. let alice = { name: 'alice' };
  1851. let bob = { name: 'bob' };
  1852. let users = [ alice, bob ];
  1853. let promises = users.map(function(user){
  1854. return resolve(user);
  1855. });
  1856. let filterFn = function(user){
  1857. // Here, Alice has permissions to create a blog post, but Bob does not.
  1858. return getPrivilegesForUser(user).then(function(privs){
  1859. return privs.can_create_blog_post === true;
  1860. });
  1861. };
  1862. filter(promises, filterFn).then(function(users){
  1863. // true, because the server told us only Alice can create a blog post.
  1864. users.length === 1;
  1865. // false, because Alice is the only user present in `users`
  1866. users[0] === bob;
  1867. });
  1868. ```
  1869. @method filter
  1870. @public
  1871. @static
  1872. @for rsvp
  1873. @param {Array} promises
  1874. @param {Function} filterFn - function to be called on each resolved value to
  1875. filter the final results.
  1876. @param {String} [label] optional string describing the promise. Useful for
  1877. tooling.
  1878. @return {Promise}
  1879. */
  1880. function filter(promises, filterFn, label) {
  1881. if (typeof filterFn !== 'function') {
  1882. return Promise.reject(new TypeError("filter expects function as a second argument"), label);
  1883. }
  1884. return Promise.resolve(promises, label)
  1885. .then(function(promises) {
  1886. if (!Array.isArray(promises)) {
  1887. throw new TypeError("filter must be called with an array");
  1888. }
  1889. return new FilterEnumerator(Promise, promises, filterFn, label).promise;
  1890. });
  1891. }
  1892. let len = 0;
  1893. let vertxNext;
  1894. function asap(callback, arg) {
  1895. queue$1[len] = callback;
  1896. queue$1[len + 1] = arg;
  1897. len += 2;
  1898. if (len === 2) {
  1899. // If len is 1, that means that we need to schedule an async flush.
  1900. // If additional callbacks are queued before the queue is flushed, they
  1901. // will be processed by this flush that we are scheduling.
  1902. scheduleFlush$1();
  1903. }
  1904. }
  1905. const browserWindow = (typeof window !== 'undefined') ? window : undefined;
  1906. const browserGlobal = browserWindow || {};
  1907. const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  1908. const isNode = typeof self === 'undefined' &&
  1909. typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  1910. // test for web worker but not in IE10
  1911. const isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  1912. typeof importScripts !== 'undefined' &&
  1913. typeof MessageChannel !== 'undefined';
  1914. // node
  1915. function useNextTick() {
  1916. let nextTick = process.nextTick;
  1917. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  1918. // setImmediate should be used instead instead
  1919. let version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
  1920. if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
  1921. nextTick = setImmediate;
  1922. }
  1923. return () => nextTick(flush);
  1924. }
  1925. // vertx
  1926. function useVertxTimer() {
  1927. if (typeof vertxNext !== 'undefined') {
  1928. return function() {
  1929. vertxNext(flush);
  1930. };
  1931. }
  1932. return useSetTimeout();
  1933. }
  1934. function useMutationObserver() {
  1935. let iterations = 0;
  1936. let observer = new BrowserMutationObserver(flush);
  1937. let node = document.createTextNode('');
  1938. observer.observe(node, { characterData: true });
  1939. return () => node.data = (iterations = ++iterations % 2);
  1940. }
  1941. // web worker
  1942. function useMessageChannel() {
  1943. let channel = new MessageChannel();
  1944. channel.port1.onmessage = flush;
  1945. return () => channel.port2.postMessage(0);
  1946. }
  1947. function useSetTimeout() {
  1948. return () => setTimeout(flush, 1);
  1949. }
  1950. const queue$1 = new Array(1000);
  1951. function flush() {
  1952. for (let i = 0; i < len; i+=2) {
  1953. let callback = queue$1[i];
  1954. let arg = queue$1[i+1];
  1955. callback(arg);
  1956. queue$1[i] = undefined;
  1957. queue$1[i+1] = undefined;
  1958. }
  1959. len = 0;
  1960. }
  1961. function attemptVertex() {
  1962. try {
  1963. const vertx = Function('return this')().require('vertx');
  1964. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  1965. return useVertxTimer();
  1966. } catch(e) {
  1967. return useSetTimeout();
  1968. }
  1969. }
  1970. let scheduleFlush$1;
  1971. // Decide what async method to use to triggering processing of queued callbacks:
  1972. if (isNode) {
  1973. scheduleFlush$1 = useNextTick();
  1974. } else if (BrowserMutationObserver) {
  1975. scheduleFlush$1 = useMutationObserver();
  1976. } else if (isWorker) {
  1977. scheduleFlush$1 = useMessageChannel();
  1978. } else if (browserWindow === undefined && typeof require === 'function') {
  1979. scheduleFlush$1 = attemptVertex();
  1980. } else {
  1981. scheduleFlush$1 = useSetTimeout();
  1982. }
  1983. // defaults
  1984. config.async = asap;
  1985. config.after = cb => setTimeout(cb, 0);
  1986. const cast = resolve$2;
  1987. const async = (callback, arg) => config.async(callback, arg);
  1988. function on() {
  1989. config.on(...arguments);
  1990. }
  1991. function off() {
  1992. config.off(...arguments);
  1993. }
  1994. // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
  1995. if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
  1996. let callbacks = window['__PROMISE_INSTRUMENTATION__'];
  1997. configure('instrument', true);
  1998. for (let eventName in callbacks) {
  1999. if (callbacks.hasOwnProperty(eventName)) {
  2000. on(eventName, callbacks[eventName]);
  2001. }
  2002. }
  2003. }
  2004. // the default export here is for backwards compat:
  2005. // https://github.com/tildeio/rsvp.js/issues/434
  2006. var rsvp = {
  2007. asap,
  2008. cast,
  2009. Promise,
  2010. EventTarget,
  2011. all: all$1,
  2012. allSettled,
  2013. race: race$1,
  2014. hash,
  2015. hashSettled,
  2016. rethrow,
  2017. defer,
  2018. denodeify,
  2019. configure,
  2020. on,
  2021. off,
  2022. resolve: resolve$2,
  2023. reject: reject$2,
  2024. map,
  2025. async,
  2026. filter
  2027. };
  2028. export default rsvp;
  2029. export { asap, cast, Promise, EventTarget, all$1 as all, allSettled, race$1 as race, hash, hashSettled, rethrow, defer, denodeify, configure, on, off, resolve$2 as resolve, reject$2 as reject, map, async, filter };
  2030. //# sourceMappingURL=rsvp.es.map