rsvp.js 73 KB

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