when.debug.js 111 KB

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