rsvp.es.js 63 KB

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