rsvp.es.js 67 KB

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