rsvp.es.js 69 KB

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