rsvp.js 68 KB

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