when.js 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624
  1. !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.when=e():"undefined"!=typeof global?global.when=e():"undefined"!=typeof self&&(self.when=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var when = module.exports = require('../when');
  3. when.callbacks = require('../callbacks');
  4. when.cancelable = require('../cancelable');
  5. when.delay = require('../delay');
  6. when.fn = require('../function');
  7. when.guard = require('../guard');
  8. when.keys = require('../keys');
  9. when.nodefn = when.node = require('../node');
  10. when.parallel = require('../parallel');
  11. when.pipeline = require('../pipeline');
  12. when.poll = require('../poll');
  13. when.sequence = require('../sequence');
  14. when.timeout = require('../timeout');
  15. },{"../callbacks":2,"../cancelable":3,"../delay":4,"../function":5,"../guard":6,"../keys":7,"../node":26,"../parallel":27,"../pipeline":28,"../poll":29,"../sequence":30,"../timeout":31,"../when":32}],2:[function(require,module,exports){
  16. /** @license MIT License (c) copyright 2013-2014 original author or authors */
  17. /**
  18. * Collection of helper functions for interacting with 'traditional',
  19. * callback-taking functions using a promise interface.
  20. *
  21. * @author Renato Zannon
  22. * @contributor Brian Cavalier
  23. */
  24. (function(define) {
  25. define(function(require) {
  26. var when = require('./when');
  27. var Promise = when.Promise;
  28. var _liftAll = require('./lib/liftAll');
  29. var slice = Array.prototype.slice;
  30. var makeApply = require('./lib/apply');
  31. var _apply = makeApply(Promise, dispatch);
  32. return {
  33. lift: lift,
  34. liftAll: liftAll,
  35. apply: apply,
  36. call: call,
  37. promisify: promisify
  38. };
  39. /**
  40. * Takes a `traditional` callback-taking function and returns a promise for its
  41. * result, accepting an optional array of arguments (that might be values or
  42. * promises). It assumes that the function takes its callback and errback as
  43. * the last two arguments. The resolution of the promise depends on whether the
  44. * function will call its callback or its errback.
  45. *
  46. * @example
  47. * var domIsLoaded = callbacks.apply($);
  48. * domIsLoaded.then(function() {
  49. * doMyDomStuff();
  50. * });
  51. *
  52. * @example
  53. * function existingAjaxyFunction(url, callback, errback) {
  54. * // Complex logic you'd rather not change
  55. * }
  56. *
  57. * var promise = callbacks.apply(existingAjaxyFunction, ["/movies.json"]);
  58. *
  59. * promise.then(function(movies) {
  60. * // Work with movies
  61. * }, function(reason) {
  62. * // Handle error
  63. * });
  64. *
  65. * @param {function} asyncFunction function to be called
  66. * @param {Array} [extraAsyncArgs] array of arguments to asyncFunction
  67. * @returns {Promise} promise for the callback value of asyncFunction
  68. */
  69. function apply(asyncFunction, extraAsyncArgs) {
  70. return _apply(asyncFunction, this, extraAsyncArgs || []);
  71. }
  72. /**
  73. * Apply helper that allows specifying thisArg
  74. * @private
  75. */
  76. function dispatch(f, thisArg, args, h) {
  77. args.push(alwaysUnary(h.resolve, h), alwaysUnary(h.reject, h));
  78. tryCatchResolve(f, thisArg, args, h);
  79. }
  80. function tryCatchResolve(f, thisArg, args, resolver) {
  81. try {
  82. f.apply(thisArg, args);
  83. } catch(e) {
  84. resolver.reject(e);
  85. }
  86. }
  87. /**
  88. * Works as `callbacks.apply` does, with the difference that the arguments to
  89. * the function are passed individually, instead of as an array.
  90. *
  91. * @example
  92. * function sumInFiveSeconds(a, b, callback) {
  93. * setTimeout(function() {
  94. * callback(a + b);
  95. * }, 5000);
  96. * }
  97. *
  98. * var sumPromise = callbacks.call(sumInFiveSeconds, 5, 10);
  99. *
  100. * // Logs '15' 5 seconds later
  101. * sumPromise.then(console.log);
  102. *
  103. * @param {function} asyncFunction function to be called
  104. * @param {...*} args arguments that will be forwarded to the function
  105. * @returns {Promise} promise for the callback value of asyncFunction
  106. */
  107. function call(asyncFunction/*, arg1, arg2...*/) {
  108. return _apply(asyncFunction, this, slice.call(arguments, 1));
  109. }
  110. /**
  111. * Takes a 'traditional' callback/errback-taking function and returns a function
  112. * that returns a promise instead. The resolution/rejection of the promise
  113. * depends on whether the original function will call its callback or its
  114. * errback.
  115. *
  116. * If additional arguments are passed to the `lift` call, they will be prepended
  117. * on the calls to the original function, much like `Function.prototype.bind`.
  118. *
  119. * The resulting function is also "promise-aware", in the sense that, if given
  120. * promises as arguments, it will wait for their resolution before executing.
  121. *
  122. * @example
  123. * function traditionalAjax(method, url, callback, errback) {
  124. * var xhr = new XMLHttpRequest();
  125. * xhr.open(method, url);
  126. *
  127. * xhr.onload = callback;
  128. * xhr.onerror = errback;
  129. *
  130. * xhr.send();
  131. * }
  132. *
  133. * var promiseAjax = callbacks.lift(traditionalAjax);
  134. * promiseAjax("GET", "/movies.json").then(console.log, console.error);
  135. *
  136. * var promiseAjaxGet = callbacks.lift(traditionalAjax, "GET");
  137. * promiseAjaxGet("/movies.json").then(console.log, console.error);
  138. *
  139. * @param {Function} f traditional async function to be decorated
  140. * @param {...*} [args] arguments to be prepended for the new function @deprecated
  141. * @returns {Function} a promise-returning function
  142. */
  143. function lift(f/*, args...*/) {
  144. var args = arguments.length > 1 ? slice.call(arguments, 1) : [];
  145. return function() {
  146. return _apply(f, this, args.concat(slice.call(arguments)));
  147. };
  148. }
  149. /**
  150. * Lift all the functions/methods on src
  151. * @param {object|function} src source whose functions will be lifted
  152. * @param {function?} combine optional function for customizing the lifting
  153. * process. It is passed dst, the lifted function, and the property name of
  154. * the original function on src.
  155. * @param {(object|function)?} dst option destination host onto which to place lifted
  156. * functions. If not provided, liftAll returns a new object.
  157. * @returns {*} If dst is provided, returns dst with lifted functions as
  158. * properties. If dst not provided, returns a new object with lifted functions.
  159. */
  160. function liftAll(src, combine, dst) {
  161. return _liftAll(lift, combine, dst, src);
  162. }
  163. /**
  164. * `promisify` is a version of `lift` that allows fine-grained control over the
  165. * arguments that passed to the underlying function. It is intended to handle
  166. * functions that don't follow the common callback and errback positions.
  167. *
  168. * The control is done by passing an object whose 'callback' and/or 'errback'
  169. * keys, whose values are the corresponding 0-based indexes of the arguments on
  170. * the function. Negative values are interpreted as being relative to the end
  171. * of the arguments array.
  172. *
  173. * If arguments are given on the call to the 'promisified' function, they are
  174. * intermingled with the callback and errback. If a promise is given among them,
  175. * the execution of the function will only occur after its resolution.
  176. *
  177. * @example
  178. * var delay = callbacks.promisify(setTimeout, {
  179. * callback: 0
  180. * });
  181. *
  182. * delay(100).then(function() {
  183. * console.log("This happens 100ms afterwards");
  184. * });
  185. *
  186. * @example
  187. * function callbackAsLast(errback, followsStandards, callback) {
  188. * if(followsStandards) {
  189. * callback("well done!");
  190. * } else {
  191. * errback("some programmers just want to watch the world burn");
  192. * }
  193. * }
  194. *
  195. * var promisified = callbacks.promisify(callbackAsLast, {
  196. * callback: -1,
  197. * errback: 0,
  198. * });
  199. *
  200. * promisified(true).then(console.log, console.error);
  201. * promisified(false).then(console.log, console.error);
  202. *
  203. * @param {Function} asyncFunction traditional function to be decorated
  204. * @param {object} positions
  205. * @param {number} [positions.callback] index at which asyncFunction expects to
  206. * receive a success callback
  207. * @param {number} [positions.errback] index at which asyncFunction expects to
  208. * receive an error callback
  209. * @returns {function} promisified function that accepts
  210. *
  211. * @deprecated
  212. */
  213. function promisify(asyncFunction, positions) {
  214. return function() {
  215. var thisArg = this;
  216. return Promise.all(arguments).then(function(args) {
  217. var p = Promise._defer();
  218. var callbackPos, errbackPos;
  219. if(typeof positions.callback === 'number') {
  220. callbackPos = normalizePosition(args, positions.callback);
  221. }
  222. if(typeof positions.errback === 'number') {
  223. errbackPos = normalizePosition(args, positions.errback);
  224. }
  225. if(errbackPos < callbackPos) {
  226. insertCallback(args, errbackPos, p._handler.reject, p._handler);
  227. insertCallback(args, callbackPos, p._handler.resolve, p._handler);
  228. } else {
  229. insertCallback(args, callbackPos, p._handler.resolve, p._handler);
  230. insertCallback(args, errbackPos, p._handler.reject, p._handler);
  231. }
  232. asyncFunction.apply(thisArg, args);
  233. return p;
  234. });
  235. };
  236. }
  237. function normalizePosition(args, pos) {
  238. return pos < 0 ? (args.length + pos + 2) : pos;
  239. }
  240. function insertCallback(args, pos, callback, thisArg) {
  241. if(typeof pos === 'number') {
  242. args.splice(pos, 0, alwaysUnary(callback, thisArg));
  243. }
  244. }
  245. function alwaysUnary(fn, thisArg) {
  246. return function() {
  247. if (arguments.length > 1) {
  248. fn.call(thisArg, slice.call(arguments));
  249. } else {
  250. fn.apply(thisArg, arguments);
  251. }
  252. };
  253. }
  254. });
  255. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  256. },{"./lib/apply":11,"./lib/liftAll":23,"./when":32}],3:[function(require,module,exports){
  257. /** @license MIT License (c) copyright B Cavalier & J Hann */
  258. /**
  259. * cancelable.js
  260. * @deprecated
  261. *
  262. * Decorator that makes a deferred "cancelable". It adds a cancel() method that
  263. * will call a special cancel handler function and then reject the deferred. The
  264. * cancel handler can be used to do resource cleanup, or anything else that should
  265. * be done before any other rejection handlers are executed.
  266. *
  267. * Usage:
  268. *
  269. * var cancelableDeferred = cancelable(when.defer(), myCancelHandler);
  270. *
  271. * @author brian@hovercraftstudios.com
  272. */
  273. (function(define) {
  274. define(function() {
  275. /**
  276. * Makes deferred cancelable, adding a cancel() method.
  277. * @deprecated
  278. *
  279. * @param deferred {Deferred} the {@link Deferred} to make cancelable
  280. * @param canceler {Function} cancel handler function to execute when this deferred
  281. * is canceled. This is guaranteed to run before all other rejection handlers.
  282. * The canceler will NOT be executed if the deferred is rejected in the standard
  283. * way, i.e. deferred.reject(). It ONLY executes if the deferred is canceled,
  284. * i.e. deferred.cancel()
  285. *
  286. * @returns deferred, with an added cancel() method.
  287. */
  288. return function(deferred, canceler) {
  289. // Add a cancel method to the deferred to reject the delegate
  290. // with the special canceled indicator.
  291. deferred.cancel = function() {
  292. try {
  293. deferred.reject(canceler(deferred));
  294. } catch(e) {
  295. deferred.reject(e);
  296. }
  297. return deferred.promise;
  298. };
  299. return deferred;
  300. };
  301. });
  302. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(); });
  303. },{}],4:[function(require,module,exports){
  304. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  305. /**
  306. * delay.js
  307. *
  308. * Helper that returns a promise that resolves after a delay.
  309. *
  310. * @author Brian Cavalier
  311. * @author John Hann
  312. */
  313. (function(define) {
  314. define(function(require) {
  315. var when = require('./when');
  316. /**
  317. * @deprecated Use when(value).delay(ms)
  318. */
  319. return function delay(msec, value) {
  320. return when(value).delay(msec);
  321. };
  322. });
  323. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  324. },{"./when":32}],5:[function(require,module,exports){
  325. /** @license MIT License (c) copyright 2013-2014 original author or authors */
  326. /**
  327. * Collection of helper functions for wrapping and executing 'traditional'
  328. * synchronous functions in a promise interface.
  329. *
  330. * @author Brian Cavalier
  331. * @contributor Renato Zannon
  332. */
  333. (function(define) {
  334. define(function(require) {
  335. var when = require('./when');
  336. var attempt = when['try'];
  337. var _liftAll = require('./lib/liftAll');
  338. var _apply = require('./lib/apply')(when.Promise);
  339. var slice = Array.prototype.slice;
  340. return {
  341. lift: lift,
  342. liftAll: liftAll,
  343. call: attempt,
  344. apply: apply,
  345. compose: compose
  346. };
  347. /**
  348. * Takes a function and an optional array of arguments (that might be promises),
  349. * and calls the function. The return value is a promise whose resolution
  350. * depends on the value returned by the function.
  351. * @param {function} f function to be called
  352. * @param {Array} [args] array of arguments to func
  353. * @returns {Promise} promise for the return value of func
  354. */
  355. function apply(f, args) {
  356. // slice args just in case the caller passed an Arguments instance
  357. return _apply(f, this, args == null ? [] : slice.call(args));
  358. }
  359. /**
  360. * Takes a 'regular' function and returns a version of that function that
  361. * returns a promise instead of a plain value, and handles thrown errors by
  362. * returning a rejected promise. Also accepts a list of arguments to be
  363. * prepended to the new function, as does Function.prototype.bind.
  364. *
  365. * The resulting function is promise-aware, in the sense that it accepts
  366. * promise arguments, and waits for their resolution.
  367. * @param {Function} f function to be bound
  368. * @param {...*} [args] arguments to be prepended for the new function @deprecated
  369. * @returns {Function} a promise-returning function
  370. */
  371. function lift(f /*, args... */) {
  372. var args = arguments.length > 1 ? slice.call(arguments, 1) : [];
  373. return function() {
  374. return _apply(f, this, args.concat(slice.call(arguments)));
  375. };
  376. }
  377. /**
  378. * Lift all the functions/methods on src
  379. * @param {object|function} src source whose functions will be lifted
  380. * @param {function?} combine optional function for customizing the lifting
  381. * process. It is passed dst, the lifted function, and the property name of
  382. * the original function on src.
  383. * @param {(object|function)?} dst option destination host onto which to place lifted
  384. * functions. If not provided, liftAll returns a new object.
  385. * @returns {*} If dst is provided, returns dst with lifted functions as
  386. * properties. If dst not provided, returns a new object with lifted functions.
  387. */
  388. function liftAll(src, combine, dst) {
  389. return _liftAll(lift, combine, dst, src);
  390. }
  391. /**
  392. * Composes multiple functions by piping their return values. It is
  393. * transparent to whether the functions return 'regular' values or promises:
  394. * the piped argument is always a resolved value. If one of the functions
  395. * throws or returns a rejected promise, the composed promise will be also
  396. * rejected.
  397. *
  398. * The arguments (or promises to arguments) given to the returned function (if
  399. * any), are passed directly to the first function on the 'pipeline'.
  400. * @param {Function} f the function to which the arguments will be passed
  401. * @param {...Function} [funcs] functions that will be composed, in order
  402. * @returns {Function} a promise-returning composition of the functions
  403. */
  404. function compose(f /*, funcs... */) {
  405. var funcs = slice.call(arguments, 1);
  406. return function() {
  407. var thisArg = this;
  408. var args = slice.call(arguments);
  409. var firstPromise = attempt.apply(thisArg, [f].concat(args));
  410. return when.reduce(funcs, function(arg, func) {
  411. return func.call(thisArg, arg);
  412. }, firstPromise);
  413. };
  414. }
  415. });
  416. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  417. },{"./lib/apply":11,"./lib/liftAll":23,"./when":32}],6:[function(require,module,exports){
  418. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  419. /**
  420. * Generalized promise concurrency guard
  421. * Adapted from original concept by Sakari Jokinen (Rocket Pack, Ltd.)
  422. *
  423. * @author Brian Cavalier
  424. * @author John Hann
  425. * @contributor Sakari Jokinen
  426. */
  427. (function(define) {
  428. define(function(require) {
  429. var when = require('./when');
  430. var slice = Array.prototype.slice;
  431. guard.n = n;
  432. return guard;
  433. /**
  434. * Creates a guarded version of f that can only be entered when the supplied
  435. * condition allows.
  436. * @param {function} condition represents a critical section that may only
  437. * be entered when allowed by the condition
  438. * @param {function} f function to guard
  439. * @returns {function} guarded version of f
  440. */
  441. function guard(condition, f) {
  442. return function() {
  443. var args = slice.call(arguments);
  444. return when(condition()).withThis(this).then(function(exit) {
  445. return when(f.apply(this, args))['finally'](exit);
  446. });
  447. };
  448. }
  449. /**
  450. * Creates a condition that allows only n simultaneous executions
  451. * of a guarded function
  452. * @param {number} allowed number of allowed simultaneous executions
  453. * @returns {function} condition function which returns a promise that
  454. * fulfills when the critical section may be entered. The fulfillment
  455. * value is a function ("notifyExit") that must be called when the critical
  456. * section has been exited.
  457. */
  458. function n(allowed) {
  459. var count = 0;
  460. var waiting = [];
  461. return function enter() {
  462. return when.promise(function(resolve) {
  463. if(count < allowed) {
  464. resolve(exit);
  465. } else {
  466. waiting.push(resolve);
  467. }
  468. count += 1;
  469. });
  470. };
  471. function exit() {
  472. count = Math.max(count - 1, 0);
  473. if(waiting.length > 0) {
  474. waiting.shift()(exit);
  475. }
  476. }
  477. }
  478. });
  479. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  480. },{"./when":32}],7:[function(require,module,exports){
  481. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  482. /**
  483. * Licensed under the MIT License at:
  484. * http://www.opensource.org/licenses/mit-license.php
  485. *
  486. * @author Brian Cavalier
  487. * @author John Hann
  488. */
  489. (function(define) { 'use strict';
  490. define(function(require) {
  491. var when = require('./when');
  492. var Promise = when.Promise;
  493. var toPromise = when.resolve;
  494. return {
  495. all: when.lift(all),
  496. map: map,
  497. settle: settle
  498. };
  499. /**
  500. * Resolve all the key-value pairs in the supplied object or promise
  501. * for an object.
  502. * @param {Promise|object} object or promise for object whose key-value pairs
  503. * will be resolved
  504. * @returns {Promise} promise for an object with the fully resolved key-value pairs
  505. */
  506. function all(object) {
  507. var p = Promise._defer();
  508. var resolver = Promise._handler(p);
  509. var results = {};
  510. var keys = Object.keys(object);
  511. var pending = keys.length;
  512. for(var i=0, k; i<keys.length; ++i) {
  513. k = keys[i];
  514. Promise._handler(object[k]).fold(settleKey, k, results, resolver);
  515. }
  516. if(pending === 0) {
  517. resolver.resolve(results);
  518. }
  519. return p;
  520. function settleKey(k, x, resolver) {
  521. /*jshint validthis:true*/
  522. this[k] = x;
  523. if(--pending === 0) {
  524. resolver.resolve(results);
  525. }
  526. }
  527. }
  528. /**
  529. * Map values in the supplied object's keys
  530. * @param {Promise|object} object or promise for object whose key-value pairs
  531. * will be reduced
  532. * @param {function(value:*, key:String):*} f mapping function which may
  533. * return either a promise or a value
  534. * @returns {Promise} promise for an object with the mapped and fully
  535. * resolved key-value pairs
  536. */
  537. function map(object, f) {
  538. return toPromise(object).then(function(object) {
  539. return all(Object.keys(object).reduce(function(o, k) {
  540. o[k] = toPromise(object[k]).fold(mapWithKey, k);
  541. return o;
  542. }, {}));
  543. });
  544. function mapWithKey(k, x) {
  545. return f(x, k);
  546. }
  547. }
  548. /**
  549. * Resolve all key-value pairs in the supplied object and return a promise
  550. * that will always fulfill with the outcome states of all input promises.
  551. * @param {object} object whose key-value pairs will be settled
  552. * @returns {Promise} promise for an object with the mapped and fully
  553. * settled key-value pairs
  554. */
  555. function settle(object) {
  556. var keys = Object.keys(object);
  557. var results = {};
  558. if(keys.length === 0) {
  559. return toPromise(results);
  560. }
  561. var p = Promise._defer();
  562. var resolver = Promise._handler(p);
  563. var promises = keys.map(function(k) { return object[k]; });
  564. when.settle(promises).then(function(states) {
  565. populateResults(keys, states, results, resolver);
  566. });
  567. return p;
  568. }
  569. function populateResults(keys, states, results, resolver) {
  570. for(var i=0; i<keys.length; i++) {
  571. results[keys[i]] = states[i];
  572. }
  573. resolver.resolve(results);
  574. }
  575. });
  576. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  577. },{"./when":32}],8:[function(require,module,exports){
  578. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  579. /** @author Brian Cavalier */
  580. /** @author John Hann */
  581. (function(define) { 'use strict';
  582. define(function (require) {
  583. var makePromise = require('./makePromise');
  584. var Scheduler = require('./Scheduler');
  585. var async = require('./env').asap;
  586. return makePromise({
  587. scheduler: new Scheduler(async)
  588. });
  589. });
  590. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  591. },{"./Scheduler":9,"./env":21,"./makePromise":24}],9:[function(require,module,exports){
  592. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  593. /** @author Brian Cavalier */
  594. /** @author John Hann */
  595. (function(define) { 'use strict';
  596. define(function() {
  597. // Credit to Twisol (https://github.com/Twisol) for suggesting
  598. // this type of extensible queue + trampoline approach for next-tick conflation.
  599. /**
  600. * Async task scheduler
  601. * @param {function} async function to schedule a single async function
  602. * @constructor
  603. */
  604. function Scheduler(async) {
  605. this._async = async;
  606. this._running = false;
  607. this._queue = this;
  608. this._queueLen = 0;
  609. this._afterQueue = {};
  610. this._afterQueueLen = 0;
  611. var self = this;
  612. this.drain = function() {
  613. self._drain();
  614. };
  615. }
  616. /**
  617. * Enqueue a task
  618. * @param {{ run:function }} task
  619. */
  620. Scheduler.prototype.enqueue = function(task) {
  621. this._queue[this._queueLen++] = task;
  622. this.run();
  623. };
  624. /**
  625. * Enqueue a task to run after the main task queue
  626. * @param {{ run:function }} task
  627. */
  628. Scheduler.prototype.afterQueue = function(task) {
  629. this._afterQueue[this._afterQueueLen++] = task;
  630. this.run();
  631. };
  632. Scheduler.prototype.run = function() {
  633. if (!this._running) {
  634. this._running = true;
  635. this._async(this.drain);
  636. }
  637. };
  638. /**
  639. * Drain the handler queue entirely, and then the after queue
  640. */
  641. Scheduler.prototype._drain = function() {
  642. var i = 0;
  643. for (; i < this._queueLen; ++i) {
  644. this._queue[i].run();
  645. this._queue[i] = void 0;
  646. }
  647. this._queueLen = 0;
  648. this._running = false;
  649. for (i = 0; i < this._afterQueueLen; ++i) {
  650. this._afterQueue[i].run();
  651. this._afterQueue[i] = void 0;
  652. }
  653. this._afterQueueLen = 0;
  654. };
  655. return Scheduler;
  656. });
  657. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  658. },{}],10:[function(require,module,exports){
  659. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  660. /** @author Brian Cavalier */
  661. /** @author John Hann */
  662. (function(define) { 'use strict';
  663. define(function() {
  664. /**
  665. * Custom error type for promises rejected by promise.timeout
  666. * @param {string} message
  667. * @constructor
  668. */
  669. function TimeoutError (message) {
  670. Error.call(this);
  671. this.message = message;
  672. this.name = TimeoutError.name;
  673. if (typeof Error.captureStackTrace === 'function') {
  674. Error.captureStackTrace(this, TimeoutError);
  675. }
  676. }
  677. TimeoutError.prototype = Object.create(Error.prototype);
  678. TimeoutError.prototype.constructor = TimeoutError;
  679. return TimeoutError;
  680. });
  681. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  682. },{}],11:[function(require,module,exports){
  683. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  684. /** @author Brian Cavalier */
  685. /** @author John Hann */
  686. (function(define) { 'use strict';
  687. define(function() {
  688. makeApply.tryCatchResolve = tryCatchResolve;
  689. return makeApply;
  690. function makeApply(Promise, call) {
  691. if(arguments.length < 2) {
  692. call = tryCatchResolve;
  693. }
  694. return apply;
  695. function apply(f, thisArg, args) {
  696. var p = Promise._defer();
  697. var l = args.length;
  698. var params = new Array(l);
  699. callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
  700. return p;
  701. }
  702. function callAndResolve(c, h) {
  703. if(c.i < 0) {
  704. return call(c.f, c.thisArg, c.params, h);
  705. }
  706. var handler = Promise._handler(c.args[c.i]);
  707. handler.fold(callAndResolveNext, c, void 0, h);
  708. }
  709. function callAndResolveNext(c, x, h) {
  710. c.params[c.i] = x;
  711. c.i -= 1;
  712. callAndResolve(c, h);
  713. }
  714. }
  715. function tryCatchResolve(f, thisArg, args, resolver) {
  716. try {
  717. resolver.resolve(f.apply(thisArg, args));
  718. } catch(e) {
  719. resolver.reject(e);
  720. }
  721. }
  722. });
  723. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  724. },{}],12:[function(require,module,exports){
  725. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  726. /** @author Brian Cavalier */
  727. /** @author John Hann */
  728. (function(define) { 'use strict';
  729. define(function(require) {
  730. var state = require('../state');
  731. var applier = require('../apply');
  732. return function array(Promise) {
  733. var applyFold = applier(Promise);
  734. var toPromise = Promise.resolve;
  735. var all = Promise.all;
  736. var ar = Array.prototype.reduce;
  737. var arr = Array.prototype.reduceRight;
  738. var slice = Array.prototype.slice;
  739. // Additional array combinators
  740. Promise.any = any;
  741. Promise.some = some;
  742. Promise.settle = settle;
  743. Promise.map = map;
  744. Promise.filter = filter;
  745. Promise.reduce = reduce;
  746. Promise.reduceRight = reduceRight;
  747. /**
  748. * When this promise fulfills with an array, do
  749. * onFulfilled.apply(void 0, array)
  750. * @param {function} onFulfilled function to apply
  751. * @returns {Promise} promise for the result of applying onFulfilled
  752. */
  753. Promise.prototype.spread = function(onFulfilled) {
  754. return this.then(all).then(function(array) {
  755. return onFulfilled.apply(this, array);
  756. });
  757. };
  758. return Promise;
  759. /**
  760. * One-winner competitive race.
  761. * Return a promise that will fulfill when one of the promises
  762. * in the input array fulfills, or will reject when all promises
  763. * have rejected.
  764. * @param {array} promises
  765. * @returns {Promise} promise for the first fulfilled value
  766. */
  767. function any(promises) {
  768. var p = Promise._defer();
  769. var resolver = p._handler;
  770. var l = promises.length>>>0;
  771. var pending = l;
  772. var errors = [];
  773. for (var h, x, i = 0; i < l; ++i) {
  774. x = promises[i];
  775. if(x === void 0 && !(i in promises)) {
  776. --pending;
  777. continue;
  778. }
  779. h = Promise._handler(x);
  780. if(h.state() > 0) {
  781. resolver.become(h);
  782. Promise._visitRemaining(promises, i, h);
  783. break;
  784. } else {
  785. h.visit(resolver, handleFulfill, handleReject);
  786. }
  787. }
  788. if(pending === 0) {
  789. resolver.reject(new RangeError('any(): array must not be empty'));
  790. }
  791. return p;
  792. function handleFulfill(x) {
  793. /*jshint validthis:true*/
  794. errors = null;
  795. this.resolve(x); // this === resolver
  796. }
  797. function handleReject(e) {
  798. /*jshint validthis:true*/
  799. if(this.resolved) { // this === resolver
  800. return;
  801. }
  802. errors.push(e);
  803. if(--pending === 0) {
  804. this.reject(errors);
  805. }
  806. }
  807. }
  808. /**
  809. * N-winner competitive race
  810. * Return a promise that will fulfill when n input promises have
  811. * fulfilled, or will reject when it becomes impossible for n
  812. * input promises to fulfill (ie when promises.length - n + 1
  813. * have rejected)
  814. * @param {array} promises
  815. * @param {number} n
  816. * @returns {Promise} promise for the earliest n fulfillment values
  817. *
  818. * @deprecated
  819. */
  820. function some(promises, n) {
  821. /*jshint maxcomplexity:7*/
  822. var p = Promise._defer();
  823. var resolver = p._handler;
  824. var results = [];
  825. var errors = [];
  826. var l = promises.length>>>0;
  827. var nFulfill = 0;
  828. var nReject;
  829. var x, i; // reused in both for() loops
  830. // First pass: count actual array items
  831. for(i=0; i<l; ++i) {
  832. x = promises[i];
  833. if(x === void 0 && !(i in promises)) {
  834. continue;
  835. }
  836. ++nFulfill;
  837. }
  838. // Compute actual goals
  839. n = Math.max(n, 0);
  840. nReject = (nFulfill - n + 1);
  841. nFulfill = Math.min(n, nFulfill);
  842. if(n > nFulfill) {
  843. resolver.reject(new RangeError('some(): array must contain at least '
  844. + n + ' item(s), but had ' + nFulfill));
  845. } else if(nFulfill === 0) {
  846. resolver.resolve(results);
  847. }
  848. // Second pass: observe each array item, make progress toward goals
  849. for(i=0; i<l; ++i) {
  850. x = promises[i];
  851. if(x === void 0 && !(i in promises)) {
  852. continue;
  853. }
  854. Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
  855. }
  856. return p;
  857. function fulfill(x) {
  858. /*jshint validthis:true*/
  859. if(this.resolved) { // this === resolver
  860. return;
  861. }
  862. results.push(x);
  863. if(--nFulfill === 0) {
  864. errors = null;
  865. this.resolve(results);
  866. }
  867. }
  868. function reject(e) {
  869. /*jshint validthis:true*/
  870. if(this.resolved) { // this === resolver
  871. return;
  872. }
  873. errors.push(e);
  874. if(--nReject === 0) {
  875. results = null;
  876. this.reject(errors);
  877. }
  878. }
  879. }
  880. /**
  881. * Apply f to the value of each promise in a list of promises
  882. * and return a new list containing the results.
  883. * @param {array} promises
  884. * @param {function(x:*, index:Number):*} f mapping function
  885. * @returns {Promise}
  886. */
  887. function map(promises, f) {
  888. return Promise._traverse(f, promises);
  889. }
  890. /**
  891. * Filter the provided array of promises using the provided predicate. Input may
  892. * contain promises and values
  893. * @param {Array} promises array of promises and values
  894. * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
  895. * Must return truthy (or promise for truthy) for items to retain.
  896. * @returns {Promise} promise that will fulfill with an array containing all items
  897. * for which predicate returned truthy.
  898. */
  899. function filter(promises, predicate) {
  900. var a = slice.call(promises);
  901. return Promise._traverse(predicate, a).then(function(keep) {
  902. return filterSync(a, keep);
  903. });
  904. }
  905. function filterSync(promises, keep) {
  906. // Safe because we know all promises have fulfilled if we've made it this far
  907. var l = keep.length;
  908. var filtered = new Array(l);
  909. for(var i=0, j=0; i<l; ++i) {
  910. if(keep[i]) {
  911. filtered[j++] = Promise._handler(promises[i]).value;
  912. }
  913. }
  914. filtered.length = j;
  915. return filtered;
  916. }
  917. /**
  918. * Return a promise that will always fulfill with an array containing
  919. * the outcome states of all input promises. The returned promise
  920. * will never reject.
  921. * @param {Array} promises
  922. * @returns {Promise} promise for array of settled state descriptors
  923. */
  924. function settle(promises) {
  925. return all(promises.map(settleOne));
  926. }
  927. function settleOne(p) {
  928. // Optimize the case where we get an already-resolved when.js promise
  929. // by extracting its state:
  930. var handler;
  931. if (p instanceof Promise) {
  932. // This is our own Promise type and we can reach its handler internals:
  933. handler = p._handler.join();
  934. }
  935. if((handler && handler.state() === 0) || !handler) {
  936. // Either still pending, or not a Promise at all:
  937. return toPromise(p).then(state.fulfilled, state.rejected);
  938. }
  939. // The promise is our own, but it is already resolved. Take a shortcut.
  940. // Since we're not actually handling the resolution, we need to disable
  941. // rejection reporting.
  942. handler._unreport();
  943. return state.inspect(handler);
  944. }
  945. /**
  946. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  947. * input may contain promises and/or values, and reduceFunc
  948. * may return either a value or a promise, *and* initialValue may
  949. * be a promise for the starting value.
  950. * @param {Array|Promise} promises array or promise for an array of anything,
  951. * may contain a mix of promises and values.
  952. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
  953. * @returns {Promise} that will resolve to the final reduced value
  954. */
  955. function reduce(promises, f /*, initialValue */) {
  956. return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
  957. : ar.call(promises, liftCombine(f));
  958. }
  959. /**
  960. * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
  961. * input may contain promises and/or values, and reduceFunc
  962. * may return either a value or a promise, *and* initialValue may
  963. * be a promise for the starting value.
  964. * @param {Array|Promise} promises array or promise for an array of anything,
  965. * may contain a mix of promises and values.
  966. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
  967. * @returns {Promise} that will resolve to the final reduced value
  968. */
  969. function reduceRight(promises, f /*, initialValue */) {
  970. return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
  971. : arr.call(promises, liftCombine(f));
  972. }
  973. function liftCombine(f) {
  974. return function(z, x, i) {
  975. return applyFold(f, void 0, [z,x,i]);
  976. };
  977. }
  978. };
  979. });
  980. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  981. },{"../apply":11,"../state":25}],13:[function(require,module,exports){
  982. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  983. /** @author Brian Cavalier */
  984. /** @author John Hann */
  985. (function(define) { 'use strict';
  986. define(function() {
  987. return function flow(Promise) {
  988. var resolve = Promise.resolve;
  989. var reject = Promise.reject;
  990. var origCatch = Promise.prototype['catch'];
  991. /**
  992. * Handle the ultimate fulfillment value or rejection reason, and assume
  993. * responsibility for all errors. If an error propagates out of result
  994. * or handleFatalError, it will be rethrown to the host, resulting in a
  995. * loud stack track on most platforms and a crash on some.
  996. * @param {function?} onResult
  997. * @param {function?} onError
  998. * @returns {undefined}
  999. */
  1000. Promise.prototype.done = function(onResult, onError) {
  1001. this._handler.visit(this._handler.receiver, onResult, onError);
  1002. };
  1003. /**
  1004. * Add Error-type and predicate matching to catch. Examples:
  1005. * promise.catch(TypeError, handleTypeError)
  1006. * .catch(predicate, handleMatchedErrors)
  1007. * .catch(handleRemainingErrors)
  1008. * @param onRejected
  1009. * @returns {*}
  1010. */
  1011. Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
  1012. if (arguments.length < 2) {
  1013. return origCatch.call(this, onRejected);
  1014. }
  1015. if(typeof onRejected !== 'function') {
  1016. return this.ensure(rejectInvalidPredicate);
  1017. }
  1018. return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
  1019. };
  1020. /**
  1021. * Wraps the provided catch handler, so that it will only be called
  1022. * if the predicate evaluates truthy
  1023. * @param {?function} handler
  1024. * @param {function} predicate
  1025. * @returns {function} conditional catch handler
  1026. */
  1027. function createCatchFilter(handler, predicate) {
  1028. return function(e) {
  1029. return evaluatePredicate(e, predicate)
  1030. ? handler.call(this, e)
  1031. : reject(e);
  1032. };
  1033. }
  1034. /**
  1035. * Ensures that onFulfilledOrRejected will be called regardless of whether
  1036. * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
  1037. * receive the promises' value or reason. Any returned value will be disregarded.
  1038. * onFulfilledOrRejected may throw or return a rejected promise to signal
  1039. * an additional error.
  1040. * @param {function} handler handler to be called regardless of
  1041. * fulfillment or rejection
  1042. * @returns {Promise}
  1043. */
  1044. Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
  1045. if(typeof handler !== 'function') {
  1046. return this;
  1047. }
  1048. return this.then(function(x) {
  1049. return runSideEffect(handler, this, identity, x);
  1050. }, function(e) {
  1051. return runSideEffect(handler, this, reject, e);
  1052. });
  1053. };
  1054. function runSideEffect (handler, thisArg, propagate, value) {
  1055. var result = handler.call(thisArg);
  1056. return maybeThenable(result)
  1057. ? propagateValue(result, propagate, value)
  1058. : propagate(value);
  1059. }
  1060. function propagateValue (result, propagate, x) {
  1061. return resolve(result).then(function () {
  1062. return propagate(x);
  1063. });
  1064. }
  1065. /**
  1066. * Recover from a failure by returning a defaultValue. If defaultValue
  1067. * is a promise, it's fulfillment value will be used. If defaultValue is
  1068. * a promise that rejects, the returned promise will reject with the
  1069. * same reason.
  1070. * @param {*} defaultValue
  1071. * @returns {Promise} new promise
  1072. */
  1073. Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
  1074. return this.then(void 0, function() {
  1075. return defaultValue;
  1076. });
  1077. };
  1078. /**
  1079. * Shortcut for .then(function() { return value; })
  1080. * @param {*} value
  1081. * @return {Promise} a promise that:
  1082. * - is fulfilled if value is not a promise, or
  1083. * - if value is a promise, will fulfill with its value, or reject
  1084. * with its reason.
  1085. */
  1086. Promise.prototype['yield'] = function(value) {
  1087. return this.then(function() {
  1088. return value;
  1089. });
  1090. };
  1091. /**
  1092. * Runs a side effect when this promise fulfills, without changing the
  1093. * fulfillment value.
  1094. * @param {function} onFulfilledSideEffect
  1095. * @returns {Promise}
  1096. */
  1097. Promise.prototype.tap = function(onFulfilledSideEffect) {
  1098. return this.then(onFulfilledSideEffect)['yield'](this);
  1099. };
  1100. return Promise;
  1101. };
  1102. function rejectInvalidPredicate() {
  1103. throw new TypeError('catch predicate must be a function');
  1104. }
  1105. function evaluatePredicate(e, predicate) {
  1106. return isError(predicate) ? e instanceof predicate : predicate(e);
  1107. }
  1108. function isError(predicate) {
  1109. return predicate === Error
  1110. || (predicate != null && predicate.prototype instanceof Error);
  1111. }
  1112. function maybeThenable(x) {
  1113. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  1114. }
  1115. function identity(x) {
  1116. return x;
  1117. }
  1118. });
  1119. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1120. },{}],14:[function(require,module,exports){
  1121. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1122. /** @author Brian Cavalier */
  1123. /** @author John Hann */
  1124. /** @author Jeff Escalante */
  1125. (function(define) { 'use strict';
  1126. define(function() {
  1127. return function fold(Promise) {
  1128. Promise.prototype.fold = function(f, z) {
  1129. var promise = this._beget();
  1130. this._handler.fold(function(z, x, to) {
  1131. Promise._handler(z).fold(function(x, z, to) {
  1132. to.resolve(f.call(this, z, x));
  1133. }, x, this, to);
  1134. }, z, promise._handler.receiver, promise._handler);
  1135. return promise;
  1136. };
  1137. return Promise;
  1138. };
  1139. });
  1140. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1141. },{}],15:[function(require,module,exports){
  1142. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1143. /** @author Brian Cavalier */
  1144. /** @author John Hann */
  1145. (function(define) { 'use strict';
  1146. define(function(require) {
  1147. var inspect = require('../state').inspect;
  1148. return function inspection(Promise) {
  1149. Promise.prototype.inspect = function() {
  1150. return inspect(Promise._handler(this));
  1151. };
  1152. return Promise;
  1153. };
  1154. });
  1155. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1156. },{"../state":25}],16:[function(require,module,exports){
  1157. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1158. /** @author Brian Cavalier */
  1159. /** @author John Hann */
  1160. (function(define) { 'use strict';
  1161. define(function() {
  1162. return function generate(Promise) {
  1163. var resolve = Promise.resolve;
  1164. Promise.iterate = iterate;
  1165. Promise.unfold = unfold;
  1166. return Promise;
  1167. /**
  1168. * @deprecated Use github.com/cujojs/most streams and most.iterate
  1169. * Generate a (potentially infinite) stream of promised values:
  1170. * x, f(x), f(f(x)), etc. until condition(x) returns true
  1171. * @param {function} f function to generate a new x from the previous x
  1172. * @param {function} condition function that, given the current x, returns
  1173. * truthy when the iterate should stop
  1174. * @param {function} handler function to handle the value produced by f
  1175. * @param {*|Promise} x starting value, may be a promise
  1176. * @return {Promise} the result of the last call to f before
  1177. * condition returns true
  1178. */
  1179. function iterate(f, condition, handler, x) {
  1180. return unfold(function(x) {
  1181. return [x, f(x)];
  1182. }, condition, handler, x);
  1183. }
  1184. /**
  1185. * @deprecated Use github.com/cujojs/most streams and most.unfold
  1186. * Generate a (potentially infinite) stream of promised values
  1187. * by applying handler(generator(seed)) iteratively until
  1188. * condition(seed) returns true.
  1189. * @param {function} unspool function that generates a [value, newSeed]
  1190. * given a seed.
  1191. * @param {function} condition function that, given the current seed, returns
  1192. * truthy when the unfold should stop
  1193. * @param {function} handler function to handle the value produced by unspool
  1194. * @param x {*|Promise} starting value, may be a promise
  1195. * @return {Promise} the result of the last value produced by unspool before
  1196. * condition returns true
  1197. */
  1198. function unfold(unspool, condition, handler, x) {
  1199. return resolve(x).then(function(seed) {
  1200. return resolve(condition(seed)).then(function(done) {
  1201. return done ? seed : resolve(unspool(seed)).spread(next);
  1202. });
  1203. });
  1204. function next(item, newSeed) {
  1205. return resolve(handler(item)).then(function() {
  1206. return unfold(unspool, condition, handler, newSeed);
  1207. });
  1208. }
  1209. }
  1210. };
  1211. });
  1212. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1213. },{}],17:[function(require,module,exports){
  1214. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1215. /** @author Brian Cavalier */
  1216. /** @author John Hann */
  1217. (function(define) { 'use strict';
  1218. define(function() {
  1219. return function progress(Promise) {
  1220. /**
  1221. * @deprecated
  1222. * Register a progress handler for this promise
  1223. * @param {function} onProgress
  1224. * @returns {Promise}
  1225. */
  1226. Promise.prototype.progress = function(onProgress) {
  1227. return this.then(void 0, void 0, onProgress);
  1228. };
  1229. return Promise;
  1230. };
  1231. });
  1232. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1233. },{}],18:[function(require,module,exports){
  1234. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1235. /** @author Brian Cavalier */
  1236. /** @author John Hann */
  1237. (function(define) { 'use strict';
  1238. define(function(require) {
  1239. var env = require('../env');
  1240. var TimeoutError = require('../TimeoutError');
  1241. function setTimeout(f, ms, x, y) {
  1242. return env.setTimer(function() {
  1243. f(x, y, ms);
  1244. }, ms);
  1245. }
  1246. return function timed(Promise) {
  1247. /**
  1248. * Return a new promise whose fulfillment value is revealed only
  1249. * after ms milliseconds
  1250. * @param {number} ms milliseconds
  1251. * @returns {Promise}
  1252. */
  1253. Promise.prototype.delay = function(ms) {
  1254. var p = this._beget();
  1255. this._handler.fold(handleDelay, ms, void 0, p._handler);
  1256. return p;
  1257. };
  1258. function handleDelay(ms, x, h) {
  1259. setTimeout(resolveDelay, ms, x, h);
  1260. }
  1261. function resolveDelay(x, h) {
  1262. h.resolve(x);
  1263. }
  1264. /**
  1265. * Return a new promise that rejects after ms milliseconds unless
  1266. * this promise fulfills earlier, in which case the returned promise
  1267. * fulfills with the same value.
  1268. * @param {number} ms milliseconds
  1269. * @param {Error|*=} reason optional rejection reason to use, defaults
  1270. * to a TimeoutError if not provided
  1271. * @returns {Promise}
  1272. */
  1273. Promise.prototype.timeout = function(ms, reason) {
  1274. var p = this._beget();
  1275. var h = p._handler;
  1276. var t = setTimeout(onTimeout, ms, reason, p._handler);
  1277. this._handler.visit(h,
  1278. function onFulfill(x) {
  1279. env.clearTimer(t);
  1280. this.resolve(x); // this = h
  1281. },
  1282. function onReject(x) {
  1283. env.clearTimer(t);
  1284. this.reject(x); // this = h
  1285. },
  1286. h.notify);
  1287. return p;
  1288. };
  1289. function onTimeout(reason, h, ms) {
  1290. var e = typeof reason === 'undefined'
  1291. ? new TimeoutError('timed out after ' + ms + 'ms')
  1292. : reason;
  1293. h.reject(e);
  1294. }
  1295. return Promise;
  1296. };
  1297. });
  1298. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1299. },{"../TimeoutError":10,"../env":21}],19:[function(require,module,exports){
  1300. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1301. /** @author Brian Cavalier */
  1302. /** @author John Hann */
  1303. (function(define) { 'use strict';
  1304. define(function(require) {
  1305. var setTimer = require('../env').setTimer;
  1306. var format = require('../format');
  1307. return function unhandledRejection(Promise) {
  1308. var logError = noop;
  1309. var logInfo = noop;
  1310. var localConsole;
  1311. if(typeof console !== 'undefined') {
  1312. // Alias console to prevent things like uglify's drop_console option from
  1313. // removing console.log/error. Unhandled rejections fall into the same
  1314. // category as uncaught exceptions, and build tools shouldn't silence them.
  1315. localConsole = console;
  1316. logError = typeof localConsole.error !== 'undefined'
  1317. ? function (e) { localConsole.error(e); }
  1318. : function (e) { localConsole.log(e); };
  1319. logInfo = typeof localConsole.info !== 'undefined'
  1320. ? function (e) { localConsole.info(e); }
  1321. : function (e) { localConsole.log(e); };
  1322. }
  1323. Promise.onPotentiallyUnhandledRejection = function(rejection) {
  1324. enqueue(report, rejection);
  1325. };
  1326. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  1327. enqueue(unreport, rejection);
  1328. };
  1329. Promise.onFatalRejection = function(rejection) {
  1330. enqueue(throwit, rejection.value);
  1331. };
  1332. var tasks = [];
  1333. var reported = [];
  1334. var running = null;
  1335. function report(r) {
  1336. if(!r.handled) {
  1337. reported.push(r);
  1338. logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
  1339. }
  1340. }
  1341. function unreport(r) {
  1342. var i = reported.indexOf(r);
  1343. if(i >= 0) {
  1344. reported.splice(i, 1);
  1345. logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
  1346. }
  1347. }
  1348. function enqueue(f, x) {
  1349. tasks.push(f, x);
  1350. if(running === null) {
  1351. running = setTimer(flush, 0);
  1352. }
  1353. }
  1354. function flush() {
  1355. running = null;
  1356. while(tasks.length > 0) {
  1357. tasks.shift()(tasks.shift());
  1358. }
  1359. }
  1360. return Promise;
  1361. };
  1362. function throwit(e) {
  1363. throw e;
  1364. }
  1365. function noop() {}
  1366. });
  1367. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1368. },{"../env":21,"../format":22}],20:[function(require,module,exports){
  1369. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1370. /** @author Brian Cavalier */
  1371. /** @author John Hann */
  1372. (function(define) { 'use strict';
  1373. define(function() {
  1374. return function addWith(Promise) {
  1375. /**
  1376. * Returns a promise whose handlers will be called with `this` set to
  1377. * the supplied receiver. Subsequent promises derived from the
  1378. * returned promise will also have their handlers called with receiver
  1379. * as `this`. Calling `with` with undefined or no arguments will return
  1380. * a promise whose handlers will again be called in the usual Promises/A+
  1381. * way (no `this`) thus safely undoing any previous `with` in the
  1382. * promise chain.
  1383. *
  1384. * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
  1385. * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
  1386. *
  1387. * @param {object} receiver `this` value for all handlers attached to
  1388. * the returned promise.
  1389. * @returns {Promise}
  1390. */
  1391. Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
  1392. var p = this._beget();
  1393. var child = p._handler;
  1394. child.receiver = receiver;
  1395. this._handler.chain(child, receiver);
  1396. return p;
  1397. };
  1398. return Promise;
  1399. };
  1400. });
  1401. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1402. },{}],21:[function(require,module,exports){
  1403. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1404. /** @author Brian Cavalier */
  1405. /** @author John Hann */
  1406. /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
  1407. (function(define) { 'use strict';
  1408. define(function(require) {
  1409. /*jshint maxcomplexity:6*/
  1410. // Sniff "best" async scheduling option
  1411. // Prefer process.nextTick or MutationObserver, then check for
  1412. // setTimeout, and finally vertx, since its the only env that doesn't
  1413. // have setTimeout
  1414. var MutationObs;
  1415. var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
  1416. // Default env
  1417. var setTimer = function(f, ms) { return setTimeout(f, ms); };
  1418. var clearTimer = function(t) { return clearTimeout(t); };
  1419. var asap = function (f) { return capturedSetTimeout(f, 0); };
  1420. // Detect specific env
  1421. if (isNode()) { // Node
  1422. asap = function (f) { return process.nextTick(f); };
  1423. } else if (MutationObs = hasMutationObserver()) { // Modern browser
  1424. asap = initMutationObserver(MutationObs);
  1425. } else if (!capturedSetTimeout) { // vert.x
  1426. var vertxRequire = require;
  1427. var vertx = vertxRequire('vertx');
  1428. setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
  1429. clearTimer = vertx.cancelTimer;
  1430. asap = vertx.runOnLoop || vertx.runOnContext;
  1431. }
  1432. return {
  1433. setTimer: setTimer,
  1434. clearTimer: clearTimer,
  1435. asap: asap
  1436. };
  1437. function isNode () {
  1438. return typeof process !== 'undefined' &&
  1439. Object.prototype.toString.call(process) === '[object process]';
  1440. }
  1441. function hasMutationObserver () {
  1442. return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
  1443. (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
  1444. }
  1445. function initMutationObserver(MutationObserver) {
  1446. var scheduled;
  1447. var node = document.createTextNode('');
  1448. var o = new MutationObserver(run);
  1449. o.observe(node, { characterData: true });
  1450. function run() {
  1451. var f = scheduled;
  1452. scheduled = void 0;
  1453. f();
  1454. }
  1455. var i = 0;
  1456. return function (f) {
  1457. scheduled = f;
  1458. node.data = (i ^= 1);
  1459. };
  1460. }
  1461. });
  1462. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1463. },{}],22:[function(require,module,exports){
  1464. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1465. /** @author Brian Cavalier */
  1466. /** @author John Hann */
  1467. (function(define) { 'use strict';
  1468. define(function() {
  1469. return {
  1470. formatError: formatError,
  1471. formatObject: formatObject,
  1472. tryStringify: tryStringify
  1473. };
  1474. /**
  1475. * Format an error into a string. If e is an Error and has a stack property,
  1476. * it's returned. Otherwise, e is formatted using formatObject, with a
  1477. * warning added about e not being a proper Error.
  1478. * @param {*} e
  1479. * @returns {String} formatted string, suitable for output to developers
  1480. */
  1481. function formatError(e) {
  1482. var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
  1483. return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
  1484. }
  1485. /**
  1486. * Format an object, detecting "plain" objects and running them through
  1487. * JSON.stringify if possible.
  1488. * @param {Object} o
  1489. * @returns {string}
  1490. */
  1491. function formatObject(o) {
  1492. var s = String(o);
  1493. if(s === '[object Object]' && typeof JSON !== 'undefined') {
  1494. s = tryStringify(o, s);
  1495. }
  1496. return s;
  1497. }
  1498. /**
  1499. * Try to return the result of JSON.stringify(x). If that fails, return
  1500. * defaultValue
  1501. * @param {*} x
  1502. * @param {*} defaultValue
  1503. * @returns {String|*} JSON.stringify(x) or defaultValue
  1504. */
  1505. function tryStringify(x, defaultValue) {
  1506. try {
  1507. return JSON.stringify(x);
  1508. } catch(e) {
  1509. return defaultValue;
  1510. }
  1511. }
  1512. });
  1513. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1514. },{}],23:[function(require,module,exports){
  1515. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1516. /** @author Brian Cavalier */
  1517. /** @author John Hann */
  1518. (function(define) { 'use strict';
  1519. define(function() {
  1520. return function liftAll(liftOne, combine, dst, src) {
  1521. if(typeof combine === 'undefined') {
  1522. combine = defaultCombine;
  1523. }
  1524. return Object.keys(src).reduce(function(dst, key) {
  1525. var f = src[key];
  1526. return typeof f === 'function' ? combine(dst, liftOne(f), key) : dst;
  1527. }, typeof dst === 'undefined' ? defaultDst(src) : dst);
  1528. };
  1529. function defaultCombine(o, f, k) {
  1530. o[k] = f;
  1531. return o;
  1532. }
  1533. function defaultDst(src) {
  1534. return typeof src === 'function' ? src.bind() : Object.create(src);
  1535. }
  1536. });
  1537. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1538. },{}],24:[function(require,module,exports){
  1539. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1540. /** @author Brian Cavalier */
  1541. /** @author John Hann */
  1542. (function(define) { 'use strict';
  1543. define(function() {
  1544. return function makePromise(environment) {
  1545. var tasks = environment.scheduler;
  1546. var emitRejection = initEmitRejection();
  1547. var objectCreate = Object.create ||
  1548. function(proto) {
  1549. function Child() {}
  1550. Child.prototype = proto;
  1551. return new Child();
  1552. };
  1553. /**
  1554. * Create a promise whose fate is determined by resolver
  1555. * @constructor
  1556. * @returns {Promise} promise
  1557. * @name Promise
  1558. */
  1559. function Promise(resolver, handler) {
  1560. this._handler = resolver === Handler ? handler : init(resolver);
  1561. }
  1562. /**
  1563. * Run the supplied resolver
  1564. * @param resolver
  1565. * @returns {Pending}
  1566. */
  1567. function init(resolver) {
  1568. var handler = new Pending();
  1569. try {
  1570. resolver(promiseResolve, promiseReject, promiseNotify);
  1571. } catch (e) {
  1572. promiseReject(e);
  1573. }
  1574. return handler;
  1575. /**
  1576. * Transition from pre-resolution state to post-resolution state, notifying
  1577. * all listeners of the ultimate fulfillment or rejection
  1578. * @param {*} x resolution value
  1579. */
  1580. function promiseResolve (x) {
  1581. handler.resolve(x);
  1582. }
  1583. /**
  1584. * Reject this promise with reason, which will be used verbatim
  1585. * @param {Error|*} reason rejection reason, strongly suggested
  1586. * to be an Error type
  1587. */
  1588. function promiseReject (reason) {
  1589. handler.reject(reason);
  1590. }
  1591. /**
  1592. * @deprecated
  1593. * Issue a progress event, notifying all progress listeners
  1594. * @param {*} x progress event payload to pass to all listeners
  1595. */
  1596. function promiseNotify (x) {
  1597. handler.notify(x);
  1598. }
  1599. }
  1600. // Creation
  1601. Promise.resolve = resolve;
  1602. Promise.reject = reject;
  1603. Promise.never = never;
  1604. Promise._defer = defer;
  1605. Promise._handler = getHandler;
  1606. /**
  1607. * Returns a trusted promise. If x is already a trusted promise, it is
  1608. * returned, otherwise returns a new trusted Promise which follows x.
  1609. * @param {*} x
  1610. * @return {Promise} promise
  1611. */
  1612. function resolve(x) {
  1613. return isPromise(x) ? x
  1614. : new Promise(Handler, new Async(getHandler(x)));
  1615. }
  1616. /**
  1617. * Return a reject promise with x as its reason (x is used verbatim)
  1618. * @param {*} x
  1619. * @returns {Promise} rejected promise
  1620. */
  1621. function reject(x) {
  1622. return new Promise(Handler, new Async(new Rejected(x)));
  1623. }
  1624. /**
  1625. * Return a promise that remains pending forever
  1626. * @returns {Promise} forever-pending promise.
  1627. */
  1628. function never() {
  1629. return foreverPendingPromise; // Should be frozen
  1630. }
  1631. /**
  1632. * Creates an internal {promise, resolver} pair
  1633. * @private
  1634. * @returns {Promise}
  1635. */
  1636. function defer() {
  1637. return new Promise(Handler, new Pending());
  1638. }
  1639. // Transformation and flow control
  1640. /**
  1641. * Transform this promise's fulfillment value, returning a new Promise
  1642. * for the transformed result. If the promise cannot be fulfilled, onRejected
  1643. * is called with the reason. onProgress *may* be called with updates toward
  1644. * this promise's fulfillment.
  1645. * @param {function=} onFulfilled fulfillment handler
  1646. * @param {function=} onRejected rejection handler
  1647. * @param {function=} onProgress @deprecated progress handler
  1648. * @return {Promise} new promise
  1649. */
  1650. Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
  1651. var parent = this._handler;
  1652. var state = parent.join().state();
  1653. if ((typeof onFulfilled !== 'function' && state > 0) ||
  1654. (typeof onRejected !== 'function' && state < 0)) {
  1655. // Short circuit: value will not change, simply share handler
  1656. return new this.constructor(Handler, parent);
  1657. }
  1658. var p = this._beget();
  1659. var child = p._handler;
  1660. parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
  1661. return p;
  1662. };
  1663. /**
  1664. * If this promise cannot be fulfilled due to an error, call onRejected to
  1665. * handle the error. Shortcut for .then(undefined, onRejected)
  1666. * @param {function?} onRejected
  1667. * @return {Promise}
  1668. */
  1669. Promise.prototype['catch'] = function(onRejected) {
  1670. return this.then(void 0, onRejected);
  1671. };
  1672. /**
  1673. * Creates a new, pending promise of the same type as this promise
  1674. * @private
  1675. * @returns {Promise}
  1676. */
  1677. Promise.prototype._beget = function() {
  1678. return begetFrom(this._handler, this.constructor);
  1679. };
  1680. function begetFrom(parent, Promise) {
  1681. var child = new Pending(parent.receiver, parent.join().context);
  1682. return new Promise(Handler, child);
  1683. }
  1684. // Array combinators
  1685. Promise.all = all;
  1686. Promise.race = race;
  1687. Promise._traverse = traverse;
  1688. /**
  1689. * Return a promise that will fulfill when all promises in the
  1690. * input array have fulfilled, or will reject when one of the
  1691. * promises rejects.
  1692. * @param {array} promises array of promises
  1693. * @returns {Promise} promise for array of fulfillment values
  1694. */
  1695. function all(promises) {
  1696. return traverseWith(snd, null, promises);
  1697. }
  1698. /**
  1699. * Array<Promise<X>> -> Promise<Array<f(X)>>
  1700. * @private
  1701. * @param {function} f function to apply to each promise's value
  1702. * @param {Array} promises array of promises
  1703. * @returns {Promise} promise for transformed values
  1704. */
  1705. function traverse(f, promises) {
  1706. return traverseWith(tryCatch2, f, promises);
  1707. }
  1708. function traverseWith(tryMap, f, promises) {
  1709. var handler = typeof f === 'function' ? mapAt : settleAt;
  1710. var resolver = new Pending();
  1711. var pending = promises.length >>> 0;
  1712. var results = new Array(pending);
  1713. for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
  1714. x = promises[i];
  1715. if (x === void 0 && !(i in promises)) {
  1716. --pending;
  1717. continue;
  1718. }
  1719. traverseAt(promises, handler, i, x, resolver);
  1720. }
  1721. if(pending === 0) {
  1722. resolver.become(new Fulfilled(results));
  1723. }
  1724. return new Promise(Handler, resolver);
  1725. function mapAt(i, x, resolver) {
  1726. if(!resolver.resolved) {
  1727. traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
  1728. }
  1729. }
  1730. function settleAt(i, x, resolver) {
  1731. results[i] = x;
  1732. if(--pending === 0) {
  1733. resolver.become(new Fulfilled(results));
  1734. }
  1735. }
  1736. }
  1737. function traverseAt(promises, handler, i, x, resolver) {
  1738. if (maybeThenable(x)) {
  1739. var h = getHandlerMaybeThenable(x);
  1740. var s = h.state();
  1741. if (s === 0) {
  1742. h.fold(handler, i, void 0, resolver);
  1743. } else if (s > 0) {
  1744. handler(i, h.value, resolver);
  1745. } else {
  1746. resolver.become(h);
  1747. visitRemaining(promises, i+1, h);
  1748. }
  1749. } else {
  1750. handler(i, x, resolver);
  1751. }
  1752. }
  1753. Promise._visitRemaining = visitRemaining;
  1754. function visitRemaining(promises, start, handler) {
  1755. for(var i=start; i<promises.length; ++i) {
  1756. markAsHandled(getHandler(promises[i]), handler);
  1757. }
  1758. }
  1759. function markAsHandled(h, handler) {
  1760. if(h === handler) {
  1761. return;
  1762. }
  1763. var s = h.state();
  1764. if(s === 0) {
  1765. h.visit(h, void 0, h._unreport);
  1766. } else if(s < 0) {
  1767. h._unreport();
  1768. }
  1769. }
  1770. /**
  1771. * Fulfill-reject competitive race. Return a promise that will settle
  1772. * to the same state as the earliest input promise to settle.
  1773. *
  1774. * WARNING: The ES6 Promise spec requires that race()ing an empty array
  1775. * must return a promise that is pending forever. This implementation
  1776. * returns a singleton forever-pending promise, the same singleton that is
  1777. * returned by Promise.never(), thus can be checked with ===
  1778. *
  1779. * @param {array} promises array of promises to race
  1780. * @returns {Promise} if input is non-empty, a promise that will settle
  1781. * to the same outcome as the earliest input promise to settle. if empty
  1782. * is empty, returns a promise that will never settle.
  1783. */
  1784. function race(promises) {
  1785. if(typeof promises !== 'object' || promises === null) {
  1786. return reject(new TypeError('non-iterable passed to race()'));
  1787. }
  1788. // Sigh, race([]) is untestable unless we return *something*
  1789. // that is recognizable without calling .then() on it.
  1790. return promises.length === 0 ? never()
  1791. : promises.length === 1 ? resolve(promises[0])
  1792. : runRace(promises);
  1793. }
  1794. function runRace(promises) {
  1795. var resolver = new Pending();
  1796. var i, x, h;
  1797. for(i=0; i<promises.length; ++i) {
  1798. x = promises[i];
  1799. if (x === void 0 && !(i in promises)) {
  1800. continue;
  1801. }
  1802. h = getHandler(x);
  1803. if(h.state() !== 0) {
  1804. resolver.become(h);
  1805. visitRemaining(promises, i+1, h);
  1806. break;
  1807. } else {
  1808. h.visit(resolver, resolver.resolve, resolver.reject);
  1809. }
  1810. }
  1811. return new Promise(Handler, resolver);
  1812. }
  1813. // Promise internals
  1814. // Below this, everything is @private
  1815. /**
  1816. * Get an appropriate handler for x, without checking for cycles
  1817. * @param {*} x
  1818. * @returns {object} handler
  1819. */
  1820. function getHandler(x) {
  1821. if(isPromise(x)) {
  1822. return x._handler.join();
  1823. }
  1824. return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
  1825. }
  1826. /**
  1827. * Get a handler for thenable x.
  1828. * NOTE: You must only call this if maybeThenable(x) == true
  1829. * @param {object|function|Promise} x
  1830. * @returns {object} handler
  1831. */
  1832. function getHandlerMaybeThenable(x) {
  1833. return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
  1834. }
  1835. /**
  1836. * Get a handler for potentially untrusted thenable x
  1837. * @param {*} x
  1838. * @returns {object} handler
  1839. */
  1840. function getHandlerUntrusted(x) {
  1841. try {
  1842. var untrustedThen = x.then;
  1843. return typeof untrustedThen === 'function'
  1844. ? new Thenable(untrustedThen, x)
  1845. : new Fulfilled(x);
  1846. } catch(e) {
  1847. return new Rejected(e);
  1848. }
  1849. }
  1850. /**
  1851. * Handler for a promise that is pending forever
  1852. * @constructor
  1853. */
  1854. function Handler() {}
  1855. Handler.prototype.when
  1856. = Handler.prototype.become
  1857. = Handler.prototype.notify // deprecated
  1858. = Handler.prototype.fail
  1859. = Handler.prototype._unreport
  1860. = Handler.prototype._report
  1861. = noop;
  1862. Handler.prototype._state = 0;
  1863. Handler.prototype.state = function() {
  1864. return this._state;
  1865. };
  1866. /**
  1867. * Recursively collapse handler chain to find the handler
  1868. * nearest to the fully resolved value.
  1869. * @returns {object} handler nearest the fully resolved value
  1870. */
  1871. Handler.prototype.join = function() {
  1872. var h = this;
  1873. while(h.handler !== void 0) {
  1874. h = h.handler;
  1875. }
  1876. return h;
  1877. };
  1878. Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
  1879. this.when({
  1880. resolver: to,
  1881. receiver: receiver,
  1882. fulfilled: fulfilled,
  1883. rejected: rejected,
  1884. progress: progress
  1885. });
  1886. };
  1887. Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
  1888. this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
  1889. };
  1890. Handler.prototype.fold = function(f, z, c, to) {
  1891. this.when(new Fold(f, z, c, to));
  1892. };
  1893. /**
  1894. * Handler that invokes fail() on any handler it becomes
  1895. * @constructor
  1896. */
  1897. function FailIfRejected() {}
  1898. inherit(Handler, FailIfRejected);
  1899. FailIfRejected.prototype.become = function(h) {
  1900. h.fail();
  1901. };
  1902. var failIfRejected = new FailIfRejected();
  1903. /**
  1904. * Handler that manages a queue of consumers waiting on a pending promise
  1905. * @constructor
  1906. */
  1907. function Pending(receiver, inheritedContext) {
  1908. Promise.createContext(this, inheritedContext);
  1909. this.consumers = void 0;
  1910. this.receiver = receiver;
  1911. this.handler = void 0;
  1912. this.resolved = false;
  1913. }
  1914. inherit(Handler, Pending);
  1915. Pending.prototype._state = 0;
  1916. Pending.prototype.resolve = function(x) {
  1917. this.become(getHandler(x));
  1918. };
  1919. Pending.prototype.reject = function(x) {
  1920. if(this.resolved) {
  1921. return;
  1922. }
  1923. this.become(new Rejected(x));
  1924. };
  1925. Pending.prototype.join = function() {
  1926. if (!this.resolved) {
  1927. return this;
  1928. }
  1929. var h = this;
  1930. while (h.handler !== void 0) {
  1931. h = h.handler;
  1932. if (h === this) {
  1933. return this.handler = cycle();
  1934. }
  1935. }
  1936. return h;
  1937. };
  1938. Pending.prototype.run = function() {
  1939. var q = this.consumers;
  1940. var handler = this.handler;
  1941. this.handler = this.handler.join();
  1942. this.consumers = void 0;
  1943. for (var i = 0; i < q.length; ++i) {
  1944. handler.when(q[i]);
  1945. }
  1946. };
  1947. Pending.prototype.become = function(handler) {
  1948. if(this.resolved) {
  1949. return;
  1950. }
  1951. this.resolved = true;
  1952. this.handler = handler;
  1953. if(this.consumers !== void 0) {
  1954. tasks.enqueue(this);
  1955. }
  1956. if(this.context !== void 0) {
  1957. handler._report(this.context);
  1958. }
  1959. };
  1960. Pending.prototype.when = function(continuation) {
  1961. if(this.resolved) {
  1962. tasks.enqueue(new ContinuationTask(continuation, this.handler));
  1963. } else {
  1964. if(this.consumers === void 0) {
  1965. this.consumers = [continuation];
  1966. } else {
  1967. this.consumers.push(continuation);
  1968. }
  1969. }
  1970. };
  1971. /**
  1972. * @deprecated
  1973. */
  1974. Pending.prototype.notify = function(x) {
  1975. if(!this.resolved) {
  1976. tasks.enqueue(new ProgressTask(x, this));
  1977. }
  1978. };
  1979. Pending.prototype.fail = function(context) {
  1980. var c = typeof context === 'undefined' ? this.context : context;
  1981. this.resolved && this.handler.join().fail(c);
  1982. };
  1983. Pending.prototype._report = function(context) {
  1984. this.resolved && this.handler.join()._report(context);
  1985. };
  1986. Pending.prototype._unreport = function() {
  1987. this.resolved && this.handler.join()._unreport();
  1988. };
  1989. /**
  1990. * Wrap another handler and force it into a future stack
  1991. * @param {object} handler
  1992. * @constructor
  1993. */
  1994. function Async(handler) {
  1995. this.handler = handler;
  1996. }
  1997. inherit(Handler, Async);
  1998. Async.prototype.when = function(continuation) {
  1999. tasks.enqueue(new ContinuationTask(continuation, this));
  2000. };
  2001. Async.prototype._report = function(context) {
  2002. this.join()._report(context);
  2003. };
  2004. Async.prototype._unreport = function() {
  2005. this.join()._unreport();
  2006. };
  2007. /**
  2008. * Handler that wraps an untrusted thenable and assimilates it in a future stack
  2009. * @param {function} then
  2010. * @param {{then: function}} thenable
  2011. * @constructor
  2012. */
  2013. function Thenable(then, thenable) {
  2014. Pending.call(this);
  2015. tasks.enqueue(new AssimilateTask(then, thenable, this));
  2016. }
  2017. inherit(Pending, Thenable);
  2018. /**
  2019. * Handler for a fulfilled promise
  2020. * @param {*} x fulfillment value
  2021. * @constructor
  2022. */
  2023. function Fulfilled(x) {
  2024. Promise.createContext(this);
  2025. this.value = x;
  2026. }
  2027. inherit(Handler, Fulfilled);
  2028. Fulfilled.prototype._state = 1;
  2029. Fulfilled.prototype.fold = function(f, z, c, to) {
  2030. runContinuation3(f, z, this, c, to);
  2031. };
  2032. Fulfilled.prototype.when = function(cont) {
  2033. runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
  2034. };
  2035. var errorId = 0;
  2036. /**
  2037. * Handler for a rejected promise
  2038. * @param {*} x rejection reason
  2039. * @constructor
  2040. */
  2041. function Rejected(x) {
  2042. Promise.createContext(this);
  2043. this.id = ++errorId;
  2044. this.value = x;
  2045. this.handled = false;
  2046. this.reported = false;
  2047. this._report();
  2048. }
  2049. inherit(Handler, Rejected);
  2050. Rejected.prototype._state = -1;
  2051. Rejected.prototype.fold = function(f, z, c, to) {
  2052. to.become(this);
  2053. };
  2054. Rejected.prototype.when = function(cont) {
  2055. if(typeof cont.rejected === 'function') {
  2056. this._unreport();
  2057. }
  2058. runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
  2059. };
  2060. Rejected.prototype._report = function(context) {
  2061. tasks.afterQueue(new ReportTask(this, context));
  2062. };
  2063. Rejected.prototype._unreport = function() {
  2064. if(this.handled) {
  2065. return;
  2066. }
  2067. this.handled = true;
  2068. tasks.afterQueue(new UnreportTask(this));
  2069. };
  2070. Rejected.prototype.fail = function(context) {
  2071. this.reported = true;
  2072. emitRejection('unhandledRejection', this);
  2073. Promise.onFatalRejection(this, context === void 0 ? this.context : context);
  2074. };
  2075. function ReportTask(rejection, context) {
  2076. this.rejection = rejection;
  2077. this.context = context;
  2078. }
  2079. ReportTask.prototype.run = function() {
  2080. if(!this.rejection.handled && !this.rejection.reported) {
  2081. this.rejection.reported = true;
  2082. emitRejection('unhandledRejection', this.rejection) ||
  2083. Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
  2084. }
  2085. };
  2086. function UnreportTask(rejection) {
  2087. this.rejection = rejection;
  2088. }
  2089. UnreportTask.prototype.run = function() {
  2090. if(this.rejection.reported) {
  2091. emitRejection('rejectionHandled', this.rejection) ||
  2092. Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
  2093. }
  2094. };
  2095. // Unhandled rejection hooks
  2096. // By default, everything is a noop
  2097. Promise.createContext
  2098. = Promise.enterContext
  2099. = Promise.exitContext
  2100. = Promise.onPotentiallyUnhandledRejection
  2101. = Promise.onPotentiallyUnhandledRejectionHandled
  2102. = Promise.onFatalRejection
  2103. = noop;
  2104. // Errors and singletons
  2105. var foreverPendingHandler = new Handler();
  2106. var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
  2107. function cycle() {
  2108. return new Rejected(new TypeError('Promise cycle'));
  2109. }
  2110. // Task runners
  2111. /**
  2112. * Run a single consumer
  2113. * @constructor
  2114. */
  2115. function ContinuationTask(continuation, handler) {
  2116. this.continuation = continuation;
  2117. this.handler = handler;
  2118. }
  2119. ContinuationTask.prototype.run = function() {
  2120. this.handler.join().when(this.continuation);
  2121. };
  2122. /**
  2123. * Run a queue of progress handlers
  2124. * @constructor
  2125. */
  2126. function ProgressTask(value, handler) {
  2127. this.handler = handler;
  2128. this.value = value;
  2129. }
  2130. ProgressTask.prototype.run = function() {
  2131. var q = this.handler.consumers;
  2132. if(q === void 0) {
  2133. return;
  2134. }
  2135. for (var c, i = 0; i < q.length; ++i) {
  2136. c = q[i];
  2137. runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
  2138. }
  2139. };
  2140. /**
  2141. * Assimilate a thenable, sending it's value to resolver
  2142. * @param {function} then
  2143. * @param {object|function} thenable
  2144. * @param {object} resolver
  2145. * @constructor
  2146. */
  2147. function AssimilateTask(then, thenable, resolver) {
  2148. this._then = then;
  2149. this.thenable = thenable;
  2150. this.resolver = resolver;
  2151. }
  2152. AssimilateTask.prototype.run = function() {
  2153. var h = this.resolver;
  2154. tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
  2155. function _resolve(x) { h.resolve(x); }
  2156. function _reject(x) { h.reject(x); }
  2157. function _notify(x) { h.notify(x); }
  2158. };
  2159. function tryAssimilate(then, thenable, resolve, reject, notify) {
  2160. try {
  2161. then.call(thenable, resolve, reject, notify);
  2162. } catch (e) {
  2163. reject(e);
  2164. }
  2165. }
  2166. /**
  2167. * Fold a handler value with z
  2168. * @constructor
  2169. */
  2170. function Fold(f, z, c, to) {
  2171. this.f = f; this.z = z; this.c = c; this.to = to;
  2172. this.resolver = failIfRejected;
  2173. this.receiver = this;
  2174. }
  2175. Fold.prototype.fulfilled = function(x) {
  2176. this.f.call(this.c, this.z, x, this.to);
  2177. };
  2178. Fold.prototype.rejected = function(x) {
  2179. this.to.reject(x);
  2180. };
  2181. Fold.prototype.progress = function(x) {
  2182. this.to.notify(x);
  2183. };
  2184. // Other helpers
  2185. /**
  2186. * @param {*} x
  2187. * @returns {boolean} true iff x is a trusted Promise
  2188. */
  2189. function isPromise(x) {
  2190. return x instanceof Promise;
  2191. }
  2192. /**
  2193. * Test just enough to rule out primitives, in order to take faster
  2194. * paths in some code
  2195. * @param {*} x
  2196. * @returns {boolean} false iff x is guaranteed *not* to be a thenable
  2197. */
  2198. function maybeThenable(x) {
  2199. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  2200. }
  2201. function runContinuation1(f, h, receiver, next) {
  2202. if(typeof f !== 'function') {
  2203. return next.become(h);
  2204. }
  2205. Promise.enterContext(h);
  2206. tryCatchReject(f, h.value, receiver, next);
  2207. Promise.exitContext();
  2208. }
  2209. function runContinuation3(f, x, h, receiver, next) {
  2210. if(typeof f !== 'function') {
  2211. return next.become(h);
  2212. }
  2213. Promise.enterContext(h);
  2214. tryCatchReject3(f, x, h.value, receiver, next);
  2215. Promise.exitContext();
  2216. }
  2217. /**
  2218. * @deprecated
  2219. */
  2220. function runNotify(f, x, h, receiver, next) {
  2221. if(typeof f !== 'function') {
  2222. return next.notify(x);
  2223. }
  2224. Promise.enterContext(h);
  2225. tryCatchReturn(f, x, receiver, next);
  2226. Promise.exitContext();
  2227. }
  2228. function tryCatch2(f, a, b) {
  2229. try {
  2230. return f(a, b);
  2231. } catch(e) {
  2232. return reject(e);
  2233. }
  2234. }
  2235. /**
  2236. * Return f.call(thisArg, x), or if it throws return a rejected promise for
  2237. * the thrown exception
  2238. */
  2239. function tryCatchReject(f, x, thisArg, next) {
  2240. try {
  2241. next.become(getHandler(f.call(thisArg, x)));
  2242. } catch(e) {
  2243. next.become(new Rejected(e));
  2244. }
  2245. }
  2246. /**
  2247. * Same as above, but includes the extra argument parameter.
  2248. */
  2249. function tryCatchReject3(f, x, y, thisArg, next) {
  2250. try {
  2251. f.call(thisArg, x, y, next);
  2252. } catch(e) {
  2253. next.become(new Rejected(e));
  2254. }
  2255. }
  2256. /**
  2257. * @deprecated
  2258. * Return f.call(thisArg, x), or if it throws, *return* the exception
  2259. */
  2260. function tryCatchReturn(f, x, thisArg, next) {
  2261. try {
  2262. next.notify(f.call(thisArg, x));
  2263. } catch(e) {
  2264. next.notify(e);
  2265. }
  2266. }
  2267. function inherit(Parent, Child) {
  2268. Child.prototype = objectCreate(Parent.prototype);
  2269. Child.prototype.constructor = Child;
  2270. }
  2271. function snd(x, y) {
  2272. return y;
  2273. }
  2274. function noop() {}
  2275. function hasCustomEvent() {
  2276. if(typeof CustomEvent === 'function') {
  2277. try {
  2278. var ev = new CustomEvent('unhandledRejection');
  2279. return ev instanceof CustomEvent;
  2280. } catch (ignoredException) {}
  2281. }
  2282. return false;
  2283. }
  2284. function hasInternetExplorerCustomEvent() {
  2285. if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
  2286. try {
  2287. // Try to create one event to make sure it's supported
  2288. var ev = document.createEvent('CustomEvent');
  2289. ev.initCustomEvent('eventType', false, true, {});
  2290. return true;
  2291. } catch (ignoredException) {}
  2292. }
  2293. return false;
  2294. }
  2295. function initEmitRejection() {
  2296. /*global process, self, CustomEvent*/
  2297. if(typeof process !== 'undefined' && process !== null
  2298. && typeof process.emit === 'function') {
  2299. // Returning falsy here means to call the default
  2300. // onPotentiallyUnhandledRejection API. This is safe even in
  2301. // browserify since process.emit always returns falsy in browserify:
  2302. // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
  2303. return function(type, rejection) {
  2304. return type === 'unhandledRejection'
  2305. ? process.emit(type, rejection.value, rejection)
  2306. : process.emit(type, rejection);
  2307. };
  2308. } else if(typeof self !== 'undefined' && hasCustomEvent()) {
  2309. return (function (self, CustomEvent) {
  2310. return function (type, rejection) {
  2311. var ev = new CustomEvent(type, {
  2312. detail: {
  2313. reason: rejection.value,
  2314. key: rejection
  2315. },
  2316. bubbles: false,
  2317. cancelable: true
  2318. });
  2319. return !self.dispatchEvent(ev);
  2320. };
  2321. }(self, CustomEvent));
  2322. } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
  2323. return (function(self, document) {
  2324. return function(type, rejection) {
  2325. var ev = document.createEvent('CustomEvent');
  2326. ev.initCustomEvent(type, false, true, {
  2327. reason: rejection.value,
  2328. key: rejection
  2329. });
  2330. return !self.dispatchEvent(ev);
  2331. };
  2332. }(self, document));
  2333. }
  2334. return noop;
  2335. }
  2336. return Promise;
  2337. };
  2338. });
  2339. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  2340. },{}],25:[function(require,module,exports){
  2341. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2342. /** @author Brian Cavalier */
  2343. /** @author John Hann */
  2344. (function(define) { 'use strict';
  2345. define(function() {
  2346. return {
  2347. pending: toPendingState,
  2348. fulfilled: toFulfilledState,
  2349. rejected: toRejectedState,
  2350. inspect: inspect
  2351. };
  2352. function toPendingState() {
  2353. return { state: 'pending' };
  2354. }
  2355. function toRejectedState(e) {
  2356. return { state: 'rejected', reason: e };
  2357. }
  2358. function toFulfilledState(x) {
  2359. return { state: 'fulfilled', value: x };
  2360. }
  2361. function inspect(handler) {
  2362. var state = handler.state();
  2363. return state === 0 ? toPendingState()
  2364. : state > 0 ? toFulfilledState(handler.value)
  2365. : toRejectedState(handler.value);
  2366. }
  2367. });
  2368. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  2369. },{}],26:[function(require,module,exports){
  2370. /** @license MIT License (c) copyright 2013 original author or authors */
  2371. /**
  2372. * Collection of helpers for interfacing with node-style asynchronous functions
  2373. * using promises.
  2374. *
  2375. * @author Brian Cavalier
  2376. * @contributor Renato Zannon
  2377. */
  2378. (function(define) {
  2379. define(function(require) {
  2380. var when = require('./when');
  2381. var _liftAll = require('./lib/liftAll');
  2382. var setTimer = require('./lib/env').setTimer;
  2383. var slice = Array.prototype.slice;
  2384. var _apply = require('./lib/apply')(when.Promise, dispatch);
  2385. return {
  2386. lift: lift,
  2387. liftAll: liftAll,
  2388. apply: apply,
  2389. call: call,
  2390. createCallback: createCallback,
  2391. bindCallback: bindCallback,
  2392. liftCallback: liftCallback
  2393. };
  2394. /**
  2395. * Takes a node-style async function and calls it immediately (with an optional
  2396. * array of arguments or promises for arguments). It returns a promise whose
  2397. * resolution depends on whether the async functions calls its callback with the
  2398. * conventional error argument or not.
  2399. *
  2400. * With this it becomes possible to leverage existing APIs while still reaping
  2401. * the benefits of promises.
  2402. *
  2403. * @example
  2404. * function onlySmallNumbers(n, callback) {
  2405. * if(n < 10) {
  2406. * callback(null, n + 10);
  2407. * } else {
  2408. * callback(new Error("Calculation failed"));
  2409. * }
  2410. * }
  2411. *
  2412. * var nodefn = require("when/node/function");
  2413. *
  2414. * // Logs '15'
  2415. * nodefn.apply(onlySmallNumbers, [5]).then(console.log, console.error);
  2416. *
  2417. * // Logs 'Calculation failed'
  2418. * nodefn.apply(onlySmallNumbers, [15]).then(console.log, console.error);
  2419. *
  2420. * @param {function} f node-style function that will be called
  2421. * @param {Array} [args] array of arguments to func
  2422. * @returns {Promise} promise for the value func passes to its callback
  2423. */
  2424. function apply(f, args) {
  2425. return _apply(f, this, args || []);
  2426. }
  2427. function dispatch(f, thisArg, args, h) {
  2428. var cb = createCallback(h);
  2429. try {
  2430. switch(args.length) {
  2431. case 2: f.call(thisArg, args[0], args[1], cb); break;
  2432. case 1: f.call(thisArg, args[0], cb); break;
  2433. case 0: f.call(thisArg, cb); break;
  2434. default:
  2435. args.push(cb);
  2436. f.apply(thisArg, args);
  2437. }
  2438. } catch(e) {
  2439. h.reject(e);
  2440. }
  2441. }
  2442. /**
  2443. * Has the same behavior that {@link apply} has, with the difference that the
  2444. * arguments to the function are provided individually, while {@link apply} accepts
  2445. * a single array.
  2446. *
  2447. * @example
  2448. * function sumSmallNumbers(x, y, callback) {
  2449. * var result = x + y;
  2450. * if(result < 10) {
  2451. * callback(null, result);
  2452. * } else {
  2453. * callback(new Error("Calculation failed"));
  2454. * }
  2455. * }
  2456. *
  2457. * // Logs '5'
  2458. * nodefn.call(sumSmallNumbers, 2, 3).then(console.log, console.error);
  2459. *
  2460. * // Logs 'Calculation failed'
  2461. * nodefn.call(sumSmallNumbers, 5, 10).then(console.log, console.error);
  2462. *
  2463. * @param {function} f node-style function that will be called
  2464. * @param {...*} [args] arguments that will be forwarded to the function
  2465. * @returns {Promise} promise for the value func passes to its callback
  2466. */
  2467. function call(f /*, args... */) {
  2468. return _apply(f, this, slice.call(arguments, 1));
  2469. }
  2470. /**
  2471. * Takes a node-style function and returns new function that wraps the
  2472. * original and, instead of taking a callback, returns a promise. Also, it
  2473. * knows how to handle promises given as arguments, waiting for their
  2474. * resolution before executing.
  2475. *
  2476. * Upon execution, the orginal function is executed as well. If it passes
  2477. * a truthy value as the first argument to the callback, it will be
  2478. * interpreted as an error condition, and the promise will be rejected
  2479. * with it. Otherwise, the call is considered a resolution, and the promise
  2480. * is resolved with the callback's second argument.
  2481. *
  2482. * @example
  2483. * var fs = require("fs"), nodefn = require("when/node/function");
  2484. *
  2485. * var promiseRead = nodefn.lift(fs.readFile);
  2486. *
  2487. * // The promise is resolved with the contents of the file if everything
  2488. * // goes ok
  2489. * promiseRead('exists.txt').then(console.log, console.error);
  2490. *
  2491. * // And will be rejected if something doesn't work out
  2492. * // (e.g. the files does not exist)
  2493. * promiseRead('doesnt_exist.txt').then(console.log, console.error);
  2494. *
  2495. *
  2496. * @param {Function} f node-style function to be lifted
  2497. * @param {...*} [args] arguments to be prepended for the new function @deprecated
  2498. * @returns {Function} a promise-returning function
  2499. */
  2500. function lift(f /*, args... */) {
  2501. var args1 = arguments.length > 1 ? slice.call(arguments, 1) : [];
  2502. return function() {
  2503. // TODO: Simplify once partialing has been removed
  2504. var l = args1.length;
  2505. var al = arguments.length;
  2506. var args = new Array(al + l);
  2507. var i;
  2508. for(i=0; i<l; ++i) {
  2509. args[i] = args1[i];
  2510. }
  2511. for(i=0; i<al; ++i) {
  2512. args[i+l] = arguments[i];
  2513. }
  2514. return _apply(f, this, args);
  2515. };
  2516. }
  2517. /**
  2518. * Lift all the functions/methods on src
  2519. * @param {object|function} src source whose functions will be lifted
  2520. * @param {function?} combine optional function for customizing the lifting
  2521. * process. It is passed dst, the lifted function, and the property name of
  2522. * the original function on src.
  2523. * @param {(object|function)?} dst option destination host onto which to place lifted
  2524. * functions. If not provided, liftAll returns a new object.
  2525. * @returns {*} If dst is provided, returns dst with lifted functions as
  2526. * properties. If dst not provided, returns a new object with lifted functions.
  2527. */
  2528. function liftAll(src, combine, dst) {
  2529. return _liftAll(lift, combine, dst, src);
  2530. }
  2531. /**
  2532. * Takes an object that responds to the resolver interface, and returns
  2533. * a function that will resolve or reject it depending on how it is called.
  2534. *
  2535. * @example
  2536. * function callbackTakingFunction(callback) {
  2537. * if(somethingWrongHappened) {
  2538. * callback(error);
  2539. * } else {
  2540. * callback(null, interestingValue);
  2541. * }
  2542. * }
  2543. *
  2544. * var when = require('when'), nodefn = require('when/node/function');
  2545. *
  2546. * var deferred = when.defer();
  2547. * callbackTakingFunction(nodefn.createCallback(deferred.resolver));
  2548. *
  2549. * deferred.promise.then(function(interestingValue) {
  2550. * // Use interestingValue
  2551. * });
  2552. *
  2553. * @param {Resolver} resolver that will be 'attached' to the callback
  2554. * @returns {Function} a node-style callback function
  2555. */
  2556. function createCallback(resolver) {
  2557. return function(err, value) {
  2558. if(err) {
  2559. resolver.reject(err);
  2560. } else if(arguments.length > 2) {
  2561. resolver.resolve(slice.call(arguments, 1));
  2562. } else {
  2563. resolver.resolve(value);
  2564. }
  2565. };
  2566. }
  2567. /**
  2568. * Attaches a node-style callback to a promise, ensuring the callback is
  2569. * called for either fulfillment or rejection. Returns a promise with the same
  2570. * state as the passed-in promise.
  2571. *
  2572. * @example
  2573. * var deferred = when.defer();
  2574. *
  2575. * function callback(err, value) {
  2576. * // Handle err or use value
  2577. * }
  2578. *
  2579. * bindCallback(deferred.promise, callback);
  2580. *
  2581. * deferred.resolve('interesting value');
  2582. *
  2583. * @param {Promise} promise The promise to be attached to.
  2584. * @param {Function} callback The node-style callback to attach.
  2585. * @returns {Promise} A promise with the same state as the passed-in promise.
  2586. */
  2587. function bindCallback(promise, callback) {
  2588. promise = when(promise);
  2589. if (callback) {
  2590. promise.then(success, wrapped);
  2591. }
  2592. return promise;
  2593. function success(value) {
  2594. wrapped(null, value);
  2595. }
  2596. function wrapped(err, value) {
  2597. setTimer(function () {
  2598. callback(err, value);
  2599. }, 0);
  2600. }
  2601. }
  2602. /**
  2603. * Takes a node-style callback and returns new function that accepts a
  2604. * promise, calling the original callback when the promise is either
  2605. * fulfilled or rejected with the appropriate arguments.
  2606. *
  2607. * @example
  2608. * var deferred = when.defer();
  2609. *
  2610. * function callback(err, value) {
  2611. * // Handle err or use value
  2612. * }
  2613. *
  2614. * var wrapped = liftCallback(callback);
  2615. *
  2616. * // `wrapped` can now be passed around at will
  2617. * wrapped(deferred.promise);
  2618. *
  2619. * deferred.resolve('interesting value');
  2620. *
  2621. * @param {Function} callback The node-style callback to wrap.
  2622. * @returns {Function} The lifted, promise-accepting function.
  2623. */
  2624. function liftCallback(callback) {
  2625. return function(promise) {
  2626. return bindCallback(promise, callback);
  2627. };
  2628. }
  2629. });
  2630. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2631. },{"./lib/apply":11,"./lib/env":21,"./lib/liftAll":23,"./when":32}],27:[function(require,module,exports){
  2632. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2633. /**
  2634. * parallel.js
  2635. *
  2636. * Run a set of task functions in parallel. All tasks will
  2637. * receive the same args
  2638. *
  2639. * @author Brian Cavalier
  2640. * @author John Hann
  2641. */
  2642. (function(define) {
  2643. define(function(require) {
  2644. var when = require('./when');
  2645. var all = when.Promise.all;
  2646. var slice = Array.prototype.slice;
  2647. /**
  2648. * Run array of tasks in parallel
  2649. * @param tasks {Array|Promise} array or promiseForArray of task functions
  2650. * @param [args] {*} arguments to be passed to all tasks
  2651. * @return {Promise} promise for array containing the
  2652. * result of each task in the array position corresponding
  2653. * to position of the task in the tasks array
  2654. */
  2655. return function parallel(tasks /*, args... */) {
  2656. return all(slice.call(arguments, 1)).then(function(args) {
  2657. return when.map(tasks, function(task) {
  2658. return task.apply(void 0, args);
  2659. });
  2660. });
  2661. };
  2662. });
  2663. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2664. },{"./when":32}],28:[function(require,module,exports){
  2665. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2666. /**
  2667. * pipeline.js
  2668. *
  2669. * Run a set of task functions in sequence, passing the result
  2670. * of the previous as an argument to the next. Like a shell
  2671. * pipeline, e.g. `cat file.txt | grep 'foo' | sed -e 's/foo/bar/g'
  2672. *
  2673. * @author Brian Cavalier
  2674. * @author John Hann
  2675. */
  2676. (function(define) {
  2677. define(function(require) {
  2678. var when = require('./when');
  2679. var all = when.Promise.all;
  2680. var slice = Array.prototype.slice;
  2681. /**
  2682. * Run array of tasks in a pipeline where the next
  2683. * tasks receives the result of the previous. The first task
  2684. * will receive the initialArgs as its argument list.
  2685. * @param tasks {Array|Promise} array or promise for array of task functions
  2686. * @param [initialArgs...] {*} arguments to be passed to the first task
  2687. * @return {Promise} promise for return value of the final task
  2688. */
  2689. return function pipeline(tasks /* initialArgs... */) {
  2690. // Self-optimizing function to run first task with multiple
  2691. // args using apply, but subsequence tasks via direct invocation
  2692. var runTask = function(args, task) {
  2693. runTask = function(arg, task) {
  2694. return task(arg);
  2695. };
  2696. return task.apply(null, args);
  2697. };
  2698. return all(slice.call(arguments, 1)).then(function(args) {
  2699. return when.reduce(tasks, function(arg, task) {
  2700. return runTask(arg, task);
  2701. }, args);
  2702. });
  2703. };
  2704. });
  2705. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2706. },{"./when":32}],29:[function(require,module,exports){
  2707. /** @license MIT License (c) copyright 2012-2013 original author or authors */
  2708. /**
  2709. * poll.js
  2710. *
  2711. * Helper that polls until cancelled or for a condition to become true.
  2712. *
  2713. * @author Scott Andrews
  2714. */
  2715. (function (define) { 'use strict';
  2716. define(function(require) {
  2717. var when = require('./when');
  2718. var attempt = when['try'];
  2719. var cancelable = require('./cancelable');
  2720. /**
  2721. * Periodically execute the task function on the msec delay. The result of
  2722. * the task may be verified by watching for a condition to become true. The
  2723. * returned deferred is cancellable if the polling needs to be cancelled
  2724. * externally before reaching a resolved state.
  2725. *
  2726. * The next vote is scheduled after the results of the current vote are
  2727. * verified and rejected.
  2728. *
  2729. * Polling may be terminated by the verifier returning a truthy value,
  2730. * invoking cancel() on the returned promise, or the task function returning
  2731. * a rejected promise.
  2732. *
  2733. * Usage:
  2734. *
  2735. * var count = 0;
  2736. * function doSomething() { return count++ }
  2737. *
  2738. * // poll until cancelled
  2739. * var p = poll(doSomething, 1000);
  2740. * ...
  2741. * p.cancel();
  2742. *
  2743. * // poll until condition is met
  2744. * poll(doSomething, 1000, function(result) { return result > 10 })
  2745. * .then(function(result) { assert result == 10 });
  2746. *
  2747. * // delay first vote
  2748. * poll(doSomething, 1000, anyFunc, true);
  2749. *
  2750. * @param task {Function} function that is executed after every timeout
  2751. * @param interval {number|Function} timeout in milliseconds
  2752. * @param [verifier] {Function} function to evaluate the result of the vote.
  2753. * May return a {Promise} or a {Boolean}. Rejecting the promise or a
  2754. * falsey value will schedule the next vote.
  2755. * @param [delayInitialTask] {boolean} if truthy, the first vote is scheduled
  2756. * instead of immediate
  2757. *
  2758. * @returns {Promise}
  2759. */
  2760. return function poll(task, interval, verifier, delayInitialTask) {
  2761. var deferred, canceled, reject;
  2762. canceled = false;
  2763. deferred = cancelable(when.defer(), function () { canceled = true; });
  2764. reject = deferred.reject;
  2765. verifier = verifier || function () { return false; };
  2766. if (typeof interval !== 'function') {
  2767. interval = (function (interval) {
  2768. return function () { return when().delay(interval); };
  2769. })(interval);
  2770. }
  2771. function certify(result) {
  2772. deferred.resolve(result);
  2773. }
  2774. function schedule(result) {
  2775. attempt(interval).then(vote, reject);
  2776. if (result !== void 0) {
  2777. deferred.notify(result);
  2778. }
  2779. }
  2780. function vote() {
  2781. if (canceled) { return; }
  2782. when(task(),
  2783. function (result) {
  2784. when(verifier(result),
  2785. function (verification) {
  2786. return verification ? certify(result) : schedule(result);
  2787. },
  2788. function () { schedule(result); }
  2789. );
  2790. },
  2791. reject
  2792. );
  2793. }
  2794. if (delayInitialTask) {
  2795. schedule();
  2796. } else {
  2797. // if task() is blocking, vote will also block
  2798. vote();
  2799. }
  2800. // make the promise cancelable
  2801. deferred.promise = Object.create(deferred.promise);
  2802. deferred.promise.cancel = deferred.cancel;
  2803. return deferred.promise;
  2804. };
  2805. });
  2806. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2807. },{"./cancelable":3,"./when":32}],30:[function(require,module,exports){
  2808. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2809. /**
  2810. * sequence.js
  2811. *
  2812. * Run a set of task functions in sequence. All tasks will
  2813. * receive the same args.
  2814. *
  2815. * @author Brian Cavalier
  2816. * @author John Hann
  2817. */
  2818. (function(define) {
  2819. define(function(require) {
  2820. var when = require('./when');
  2821. var all = when.Promise.all;
  2822. var slice = Array.prototype.slice;
  2823. /**
  2824. * Run array of tasks in sequence with no overlap
  2825. * @param tasks {Array|Promise} array or promiseForArray of task functions
  2826. * @param [args] {*} arguments to be passed to all tasks
  2827. * @return {Promise} promise for an array containing
  2828. * the result of each task in the array position corresponding
  2829. * to position of the task in the tasks array
  2830. */
  2831. return function sequence(tasks /*, args... */) {
  2832. var results = [];
  2833. return all(slice.call(arguments, 1)).then(function(args) {
  2834. return when.reduce(tasks, function(results, task) {
  2835. return when(task.apply(void 0, args), addResult);
  2836. }, results);
  2837. });
  2838. function addResult(result) {
  2839. results.push(result);
  2840. return results;
  2841. }
  2842. };
  2843. });
  2844. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2845. },{"./when":32}],31:[function(require,module,exports){
  2846. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2847. /**
  2848. * timeout.js
  2849. *
  2850. * Helper that returns a promise that rejects after a specified timeout,
  2851. * if not explicitly resolved or rejected before that.
  2852. *
  2853. * @author Brian Cavalier
  2854. * @author John Hann
  2855. */
  2856. (function(define) {
  2857. define(function(require) {
  2858. var when = require('./when');
  2859. /**
  2860. * @deprecated Use when(trigger).timeout(ms)
  2861. */
  2862. return function timeout(msec, trigger) {
  2863. return when(trigger).timeout(msec);
  2864. };
  2865. });
  2866. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2867. },{"./when":32}],32:[function(require,module,exports){
  2868. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2869. /**
  2870. * Promises/A+ and when() implementation
  2871. * when is part of the cujoJS family of libraries (http://cujojs.com/)
  2872. * @author Brian Cavalier
  2873. * @author John Hann
  2874. */
  2875. (function(define) { 'use strict';
  2876. define(function (require) {
  2877. var timed = require('./lib/decorators/timed');
  2878. var array = require('./lib/decorators/array');
  2879. var flow = require('./lib/decorators/flow');
  2880. var fold = require('./lib/decorators/fold');
  2881. var inspect = require('./lib/decorators/inspect');
  2882. var generate = require('./lib/decorators/iterate');
  2883. var progress = require('./lib/decorators/progress');
  2884. var withThis = require('./lib/decorators/with');
  2885. var unhandledRejection = require('./lib/decorators/unhandledRejection');
  2886. var TimeoutError = require('./lib/TimeoutError');
  2887. var Promise = [array, flow, fold, generate, progress,
  2888. inspect, withThis, timed, unhandledRejection]
  2889. .reduce(function(Promise, feature) {
  2890. return feature(Promise);
  2891. }, require('./lib/Promise'));
  2892. var apply = require('./lib/apply')(Promise);
  2893. // Public API
  2894. when.promise = promise; // Create a pending promise
  2895. when.resolve = Promise.resolve; // Create a resolved promise
  2896. when.reject = Promise.reject; // Create a rejected promise
  2897. when.lift = lift; // lift a function to return promises
  2898. when['try'] = attempt; // call a function and return a promise
  2899. when.attempt = attempt; // alias for when.try
  2900. when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
  2901. when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
  2902. when.join = join; // Join 2 or more promises
  2903. when.all = all; // Resolve a list of promises
  2904. when.settle = settle; // Settle a list of promises
  2905. when.any = lift(Promise.any); // One-winner race
  2906. when.some = lift(Promise.some); // Multi-winner race
  2907. when.race = lift(Promise.race); // First-to-settle race
  2908. when.map = map; // Array.map() for promises
  2909. when.filter = filter; // Array.filter() for promises
  2910. when.reduce = lift(Promise.reduce); // Array.reduce() for promises
  2911. when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
  2912. when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
  2913. when.Promise = Promise; // Promise constructor
  2914. when.defer = defer; // Create a {promise, resolve, reject} tuple
  2915. // Error types
  2916. when.TimeoutError = TimeoutError;
  2917. /**
  2918. * Get a trusted promise for x, or by transforming x with onFulfilled
  2919. *
  2920. * @param {*} x
  2921. * @param {function?} onFulfilled callback to be called when x is
  2922. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  2923. * will be invoked immediately.
  2924. * @param {function?} onRejected callback to be called when x is
  2925. * rejected.
  2926. * @param {function?} onProgress callback to be called when progress updates
  2927. * are issued for x. @deprecated
  2928. * @returns {Promise} a new promise that will fulfill with the return
  2929. * value of callback or errback or the completion value of promiseOrValue if
  2930. * callback and/or errback is not supplied.
  2931. */
  2932. function when(x, onFulfilled, onRejected, onProgress) {
  2933. var p = Promise.resolve(x);
  2934. if (arguments.length < 2) {
  2935. return p;
  2936. }
  2937. return p.then(onFulfilled, onRejected, onProgress);
  2938. }
  2939. /**
  2940. * Creates a new promise whose fate is determined by resolver.
  2941. * @param {function} resolver function(resolve, reject, notify)
  2942. * @returns {Promise} promise whose fate is determine by resolver
  2943. */
  2944. function promise(resolver) {
  2945. return new Promise(resolver);
  2946. }
  2947. /**
  2948. * Lift the supplied function, creating a version of f that returns
  2949. * promises, and accepts promises as arguments.
  2950. * @param {function} f
  2951. * @returns {Function} version of f that returns promises
  2952. */
  2953. function lift(f) {
  2954. return function() {
  2955. for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
  2956. a[i] = arguments[i];
  2957. }
  2958. return apply(f, this, a);
  2959. };
  2960. }
  2961. /**
  2962. * Call f in a future turn, with the supplied args, and return a promise
  2963. * for the result.
  2964. * @param {function} f
  2965. * @returns {Promise}
  2966. */
  2967. function attempt(f /*, args... */) {
  2968. /*jshint validthis:true */
  2969. for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
  2970. a[i] = arguments[i+1];
  2971. }
  2972. return apply(f, this, a);
  2973. }
  2974. /**
  2975. * Creates a {promise, resolver} pair, either or both of which
  2976. * may be given out safely to consumers.
  2977. * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
  2978. */
  2979. function defer() {
  2980. return new Deferred();
  2981. }
  2982. function Deferred() {
  2983. var p = Promise._defer();
  2984. function resolve(x) { p._handler.resolve(x); }
  2985. function reject(x) { p._handler.reject(x); }
  2986. function notify(x) { p._handler.notify(x); }
  2987. this.promise = p;
  2988. this.resolve = resolve;
  2989. this.reject = reject;
  2990. this.notify = notify;
  2991. this.resolver = { resolve: resolve, reject: reject, notify: notify };
  2992. }
  2993. /**
  2994. * Determines if x is promise-like, i.e. a thenable object
  2995. * NOTE: Will return true for *any thenable object*, and isn't truly
  2996. * safe, since it may attempt to access the `then` property of x (i.e.
  2997. * clever/malicious getters may do weird things)
  2998. * @param {*} x anything
  2999. * @returns {boolean} true if x is promise-like
  3000. */
  3001. function isPromiseLike(x) {
  3002. return x && typeof x.then === 'function';
  3003. }
  3004. /**
  3005. * Return a promise that will resolve only once all the supplied arguments
  3006. * have resolved. The resolution value of the returned promise will be an array
  3007. * containing the resolution values of each of the arguments.
  3008. * @param {...*} arguments may be a mix of promises and values
  3009. * @returns {Promise}
  3010. */
  3011. function join(/* ...promises */) {
  3012. return Promise.all(arguments);
  3013. }
  3014. /**
  3015. * Return a promise that will fulfill once all input promises have
  3016. * fulfilled, or reject when any one input promise rejects.
  3017. * @param {array|Promise} promises array (or promise for an array) of promises
  3018. * @returns {Promise}
  3019. */
  3020. function all(promises) {
  3021. return when(promises, Promise.all);
  3022. }
  3023. /**
  3024. * Return a promise that will always fulfill with an array containing
  3025. * the outcome states of all input promises. The returned promise
  3026. * will only reject if `promises` itself is a rejected promise.
  3027. * @param {array|Promise} promises array (or promise for an array) of promises
  3028. * @returns {Promise} promise for array of settled state descriptors
  3029. */
  3030. function settle(promises) {
  3031. return when(promises, Promise.settle);
  3032. }
  3033. /**
  3034. * Promise-aware array map function, similar to `Array.prototype.map()`,
  3035. * but input array may contain promises or values.
  3036. * @param {Array|Promise} promises array of anything, may contain promises and values
  3037. * @param {function(x:*, index:Number):*} mapFunc map function which may
  3038. * return a promise or value
  3039. * @returns {Promise} promise that will fulfill with an array of mapped values
  3040. * or reject if any input promise rejects.
  3041. */
  3042. function map(promises, mapFunc) {
  3043. return when(promises, function(promises) {
  3044. return Promise.map(promises, mapFunc);
  3045. });
  3046. }
  3047. /**
  3048. * Filter the provided array of promises using the provided predicate. Input may
  3049. * contain promises and values
  3050. * @param {Array|Promise} promises array of promises and values
  3051. * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
  3052. * Must return truthy (or promise for truthy) for items to retain.
  3053. * @returns {Promise} promise that will fulfill with an array containing all items
  3054. * for which predicate returned truthy.
  3055. */
  3056. function filter(promises, predicate) {
  3057. return when(promises, function(promises) {
  3058. return Promise.filter(promises, predicate);
  3059. });
  3060. }
  3061. return when;
  3062. });
  3063. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  3064. },{"./lib/Promise":8,"./lib/TimeoutError":10,"./lib/apply":11,"./lib/decorators/array":12,"./lib/decorators/flow":13,"./lib/decorators/fold":14,"./lib/decorators/inspect":15,"./lib/decorators/iterate":16,"./lib/decorators/progress":17,"./lib/decorators/timed":18,"./lib/decorators/unhandledRejection":19,"./lib/decorators/with":20}]},{},[1])
  3065. //# sourceMappingURL=when.js.map
  3066. (1)
  3067. });
  3068. ;