when.debug.js 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021
  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. var h = Promise._handler(p);
  932. if(h.state() === 0) {
  933. return toPromise(p).then(state.fulfilled, state.rejected);
  934. }
  935. h._unreport();
  936. return state.inspect(h);
  937. }
  938. /**
  939. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  940. * input may contain promises and/or values, and reduceFunc
  941. * may return either a value or a promise, *and* initialValue may
  942. * be a promise for the starting value.
  943. * @param {Array|Promise} promises array or promise for an array of anything,
  944. * may contain a mix of promises and values.
  945. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
  946. * @returns {Promise} that will resolve to the final reduced value
  947. */
  948. function reduce(promises, f /*, initialValue */) {
  949. return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
  950. : ar.call(promises, liftCombine(f));
  951. }
  952. /**
  953. * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
  954. * input may contain promises and/or values, and reduceFunc
  955. * may return either a value or a promise, *and* initialValue may
  956. * be a promise for the starting value.
  957. * @param {Array|Promise} promises array or promise for an array of anything,
  958. * may contain a mix of promises and values.
  959. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
  960. * @returns {Promise} that will resolve to the final reduced value
  961. */
  962. function reduceRight(promises, f /*, initialValue */) {
  963. return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
  964. : arr.call(promises, liftCombine(f));
  965. }
  966. function liftCombine(f) {
  967. return function(z, x, i) {
  968. return applyFold(f, void 0, [z,x,i]);
  969. };
  970. }
  971. };
  972. });
  973. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  974. },{"../apply":12,"../state":26}],14:[function(require,module,exports){
  975. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  976. /** @author Brian Cavalier */
  977. /** @author John Hann */
  978. (function(define) { 'use strict';
  979. define(function() {
  980. return function flow(Promise) {
  981. var resolve = Promise.resolve;
  982. var reject = Promise.reject;
  983. var origCatch = Promise.prototype['catch'];
  984. /**
  985. * Handle the ultimate fulfillment value or rejection reason, and assume
  986. * responsibility for all errors. If an error propagates out of result
  987. * or handleFatalError, it will be rethrown to the host, resulting in a
  988. * loud stack track on most platforms and a crash on some.
  989. * @param {function?} onResult
  990. * @param {function?} onError
  991. * @returns {undefined}
  992. */
  993. Promise.prototype.done = function(onResult, onError) {
  994. this._handler.visit(this._handler.receiver, onResult, onError);
  995. };
  996. /**
  997. * Add Error-type and predicate matching to catch. Examples:
  998. * promise.catch(TypeError, handleTypeError)
  999. * .catch(predicate, handleMatchedErrors)
  1000. * .catch(handleRemainingErrors)
  1001. * @param onRejected
  1002. * @returns {*}
  1003. */
  1004. Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
  1005. if (arguments.length < 2) {
  1006. return origCatch.call(this, onRejected);
  1007. }
  1008. if(typeof onRejected !== 'function') {
  1009. return this.ensure(rejectInvalidPredicate);
  1010. }
  1011. return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
  1012. };
  1013. /**
  1014. * Wraps the provided catch handler, so that it will only be called
  1015. * if the predicate evaluates truthy
  1016. * @param {?function} handler
  1017. * @param {function} predicate
  1018. * @returns {function} conditional catch handler
  1019. */
  1020. function createCatchFilter(handler, predicate) {
  1021. return function(e) {
  1022. return evaluatePredicate(e, predicate)
  1023. ? handler.call(this, e)
  1024. : reject(e);
  1025. };
  1026. }
  1027. /**
  1028. * Ensures that onFulfilledOrRejected will be called regardless of whether
  1029. * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
  1030. * receive the promises' value or reason. Any returned value will be disregarded.
  1031. * onFulfilledOrRejected may throw or return a rejected promise to signal
  1032. * an additional error.
  1033. * @param {function} handler handler to be called regardless of
  1034. * fulfillment or rejection
  1035. * @returns {Promise}
  1036. */
  1037. Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
  1038. if(typeof handler !== 'function') {
  1039. return this;
  1040. }
  1041. return this.then(function(x) {
  1042. return runSideEffect(handler, this, identity, x);
  1043. }, function(e) {
  1044. return runSideEffect(handler, this, reject, e);
  1045. });
  1046. };
  1047. function runSideEffect (handler, thisArg, propagate, value) {
  1048. var result = handler.call(thisArg);
  1049. return maybeThenable(result)
  1050. ? propagateValue(result, propagate, value)
  1051. : propagate(value);
  1052. }
  1053. function propagateValue (result, propagate, x) {
  1054. return resolve(result).then(function () {
  1055. return propagate(x);
  1056. });
  1057. }
  1058. /**
  1059. * Recover from a failure by returning a defaultValue. If defaultValue
  1060. * is a promise, it's fulfillment value will be used. If defaultValue is
  1061. * a promise that rejects, the returned promise will reject with the
  1062. * same reason.
  1063. * @param {*} defaultValue
  1064. * @returns {Promise} new promise
  1065. */
  1066. Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
  1067. return this.then(void 0, function() {
  1068. return defaultValue;
  1069. });
  1070. };
  1071. /**
  1072. * Shortcut for .then(function() { return value; })
  1073. * @param {*} value
  1074. * @return {Promise} a promise that:
  1075. * - is fulfilled if value is not a promise, or
  1076. * - if value is a promise, will fulfill with its value, or reject
  1077. * with its reason.
  1078. */
  1079. Promise.prototype['yield'] = function(value) {
  1080. return this.then(function() {
  1081. return value;
  1082. });
  1083. };
  1084. /**
  1085. * Runs a side effect when this promise fulfills, without changing the
  1086. * fulfillment value.
  1087. * @param {function} onFulfilledSideEffect
  1088. * @returns {Promise}
  1089. */
  1090. Promise.prototype.tap = function(onFulfilledSideEffect) {
  1091. return this.then(onFulfilledSideEffect)['yield'](this);
  1092. };
  1093. return Promise;
  1094. };
  1095. function rejectInvalidPredicate() {
  1096. throw new TypeError('catch predicate must be a function');
  1097. }
  1098. function evaluatePredicate(e, predicate) {
  1099. return isError(predicate) ? e instanceof predicate : predicate(e);
  1100. }
  1101. function isError(predicate) {
  1102. return predicate === Error
  1103. || (predicate != null && predicate.prototype instanceof Error);
  1104. }
  1105. function maybeThenable(x) {
  1106. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  1107. }
  1108. function identity(x) {
  1109. return x;
  1110. }
  1111. });
  1112. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1113. },{}],15:[function(require,module,exports){
  1114. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1115. /** @author Brian Cavalier */
  1116. /** @author John Hann */
  1117. /** @author Jeff Escalante */
  1118. (function(define) { 'use strict';
  1119. define(function() {
  1120. return function fold(Promise) {
  1121. Promise.prototype.fold = function(f, z) {
  1122. var promise = this._beget();
  1123. this._handler.fold(function(z, x, to) {
  1124. Promise._handler(z).fold(function(x, z, to) {
  1125. to.resolve(f.call(this, z, x));
  1126. }, x, this, to);
  1127. }, z, promise._handler.receiver, promise._handler);
  1128. return promise;
  1129. };
  1130. return Promise;
  1131. };
  1132. });
  1133. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1134. },{}],16:[function(require,module,exports){
  1135. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1136. /** @author Brian Cavalier */
  1137. /** @author John Hann */
  1138. (function(define) { 'use strict';
  1139. define(function(require) {
  1140. var inspect = require('../state').inspect;
  1141. return function inspection(Promise) {
  1142. Promise.prototype.inspect = function() {
  1143. return inspect(Promise._handler(this));
  1144. };
  1145. return Promise;
  1146. };
  1147. });
  1148. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1149. },{"../state":26}],17:[function(require,module,exports){
  1150. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1151. /** @author Brian Cavalier */
  1152. /** @author John Hann */
  1153. (function(define) { 'use strict';
  1154. define(function() {
  1155. return function generate(Promise) {
  1156. var resolve = Promise.resolve;
  1157. Promise.iterate = iterate;
  1158. Promise.unfold = unfold;
  1159. return Promise;
  1160. /**
  1161. * @deprecated Use github.com/cujojs/most streams and most.iterate
  1162. * Generate a (potentially infinite) stream of promised values:
  1163. * x, f(x), f(f(x)), etc. until condition(x) returns true
  1164. * @param {function} f function to generate a new x from the previous x
  1165. * @param {function} condition function that, given the current x, returns
  1166. * truthy when the iterate should stop
  1167. * @param {function} handler function to handle the value produced by f
  1168. * @param {*|Promise} x starting value, may be a promise
  1169. * @return {Promise} the result of the last call to f before
  1170. * condition returns true
  1171. */
  1172. function iterate(f, condition, handler, x) {
  1173. return unfold(function(x) {
  1174. return [x, f(x)];
  1175. }, condition, handler, x);
  1176. }
  1177. /**
  1178. * @deprecated Use github.com/cujojs/most streams and most.unfold
  1179. * Generate a (potentially infinite) stream of promised values
  1180. * by applying handler(generator(seed)) iteratively until
  1181. * condition(seed) returns true.
  1182. * @param {function} unspool function that generates a [value, newSeed]
  1183. * given a seed.
  1184. * @param {function} condition function that, given the current seed, returns
  1185. * truthy when the unfold should stop
  1186. * @param {function} handler function to handle the value produced by unspool
  1187. * @param x {*|Promise} starting value, may be a promise
  1188. * @return {Promise} the result of the last value produced by unspool before
  1189. * condition returns true
  1190. */
  1191. function unfold(unspool, condition, handler, x) {
  1192. return resolve(x).then(function(seed) {
  1193. return resolve(condition(seed)).then(function(done) {
  1194. return done ? seed : resolve(unspool(seed)).spread(next);
  1195. });
  1196. });
  1197. function next(item, newSeed) {
  1198. return resolve(handler(item)).then(function() {
  1199. return unfold(unspool, condition, handler, newSeed);
  1200. });
  1201. }
  1202. }
  1203. };
  1204. });
  1205. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1206. },{}],18:[function(require,module,exports){
  1207. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1208. /** @author Brian Cavalier */
  1209. /** @author John Hann */
  1210. (function(define) { 'use strict';
  1211. define(function() {
  1212. return function progress(Promise) {
  1213. /**
  1214. * @deprecated
  1215. * Register a progress handler for this promise
  1216. * @param {function} onProgress
  1217. * @returns {Promise}
  1218. */
  1219. Promise.prototype.progress = function(onProgress) {
  1220. return this.then(void 0, void 0, onProgress);
  1221. };
  1222. return Promise;
  1223. };
  1224. });
  1225. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1226. },{}],19:[function(require,module,exports){
  1227. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1228. /** @author Brian Cavalier */
  1229. /** @author John Hann */
  1230. (function(define) { 'use strict';
  1231. define(function(require) {
  1232. var env = require('../env');
  1233. var TimeoutError = require('../TimeoutError');
  1234. function setTimeout(f, ms, x, y) {
  1235. return env.setTimer(function() {
  1236. f(x, y, ms);
  1237. }, ms);
  1238. }
  1239. return function timed(Promise) {
  1240. /**
  1241. * Return a new promise whose fulfillment value is revealed only
  1242. * after ms milliseconds
  1243. * @param {number} ms milliseconds
  1244. * @returns {Promise}
  1245. */
  1246. Promise.prototype.delay = function(ms) {
  1247. var p = this._beget();
  1248. this._handler.fold(handleDelay, ms, void 0, p._handler);
  1249. return p;
  1250. };
  1251. function handleDelay(ms, x, h) {
  1252. setTimeout(resolveDelay, ms, x, h);
  1253. }
  1254. function resolveDelay(x, h) {
  1255. h.resolve(x);
  1256. }
  1257. /**
  1258. * Return a new promise that rejects after ms milliseconds unless
  1259. * this promise fulfills earlier, in which case the returned promise
  1260. * fulfills with the same value.
  1261. * @param {number} ms milliseconds
  1262. * @param {Error|*=} reason optional rejection reason to use, defaults
  1263. * to a TimeoutError if not provided
  1264. * @returns {Promise}
  1265. */
  1266. Promise.prototype.timeout = function(ms, reason) {
  1267. var p = this._beget();
  1268. var h = p._handler;
  1269. var t = setTimeout(onTimeout, ms, reason, p._handler);
  1270. this._handler.visit(h,
  1271. function onFulfill(x) {
  1272. env.clearTimer(t);
  1273. this.resolve(x); // this = h
  1274. },
  1275. function onReject(x) {
  1276. env.clearTimer(t);
  1277. this.reject(x); // this = h
  1278. },
  1279. h.notify);
  1280. return p;
  1281. };
  1282. function onTimeout(reason, h, ms) {
  1283. var e = typeof reason === 'undefined'
  1284. ? new TimeoutError('timed out after ' + ms + 'ms')
  1285. : reason;
  1286. h.reject(e);
  1287. }
  1288. return Promise;
  1289. };
  1290. });
  1291. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1292. },{"../TimeoutError":11,"../env":22}],20:[function(require,module,exports){
  1293. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1294. /** @author Brian Cavalier */
  1295. /** @author John Hann */
  1296. (function(define) { 'use strict';
  1297. define(function(require) {
  1298. var setTimer = require('../env').setTimer;
  1299. var format = require('../format');
  1300. return function unhandledRejection(Promise) {
  1301. var logError = noop;
  1302. var logInfo = noop;
  1303. var localConsole;
  1304. if(typeof console !== 'undefined') {
  1305. // Alias console to prevent things like uglify's drop_console option from
  1306. // removing console.log/error. Unhandled rejections fall into the same
  1307. // category as uncaught exceptions, and build tools shouldn't silence them.
  1308. localConsole = console;
  1309. logError = typeof localConsole.error !== 'undefined'
  1310. ? function (e) { localConsole.error(e); }
  1311. : function (e) { localConsole.log(e); };
  1312. logInfo = typeof localConsole.info !== 'undefined'
  1313. ? function (e) { localConsole.info(e); }
  1314. : function (e) { localConsole.log(e); };
  1315. }
  1316. Promise.onPotentiallyUnhandledRejection = function(rejection) {
  1317. enqueue(report, rejection);
  1318. };
  1319. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  1320. enqueue(unreport, rejection);
  1321. };
  1322. Promise.onFatalRejection = function(rejection) {
  1323. enqueue(throwit, rejection.value);
  1324. };
  1325. var tasks = [];
  1326. var reported = [];
  1327. var running = null;
  1328. function report(r) {
  1329. if(!r.handled) {
  1330. reported.push(r);
  1331. logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
  1332. }
  1333. }
  1334. function unreport(r) {
  1335. var i = reported.indexOf(r);
  1336. if(i >= 0) {
  1337. reported.splice(i, 1);
  1338. logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
  1339. }
  1340. }
  1341. function enqueue(f, x) {
  1342. tasks.push(f, x);
  1343. if(running === null) {
  1344. running = setTimer(flush, 0);
  1345. }
  1346. }
  1347. function flush() {
  1348. running = null;
  1349. while(tasks.length > 0) {
  1350. tasks.shift()(tasks.shift());
  1351. }
  1352. }
  1353. return Promise;
  1354. };
  1355. function throwit(e) {
  1356. throw e;
  1357. }
  1358. function noop() {}
  1359. });
  1360. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1361. },{"../env":22,"../format":23}],21:[function(require,module,exports){
  1362. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1363. /** @author Brian Cavalier */
  1364. /** @author John Hann */
  1365. (function(define) { 'use strict';
  1366. define(function() {
  1367. return function addWith(Promise) {
  1368. /**
  1369. * Returns a promise whose handlers will be called with `this` set to
  1370. * the supplied receiver. Subsequent promises derived from the
  1371. * returned promise will also have their handlers called with receiver
  1372. * as `this`. Calling `with` with undefined or no arguments will return
  1373. * a promise whose handlers will again be called in the usual Promises/A+
  1374. * way (no `this`) thus safely undoing any previous `with` in the
  1375. * promise chain.
  1376. *
  1377. * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
  1378. * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
  1379. *
  1380. * @param {object} receiver `this` value for all handlers attached to
  1381. * the returned promise.
  1382. * @returns {Promise}
  1383. */
  1384. Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
  1385. var p = this._beget();
  1386. var child = p._handler;
  1387. child.receiver = receiver;
  1388. this._handler.chain(child, receiver);
  1389. return p;
  1390. };
  1391. return Promise;
  1392. };
  1393. });
  1394. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1395. },{}],22:[function(require,module,exports){
  1396. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1397. /** @author Brian Cavalier */
  1398. /** @author John Hann */
  1399. /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
  1400. (function(define) { 'use strict';
  1401. define(function(require) {
  1402. /*jshint maxcomplexity:6*/
  1403. // Sniff "best" async scheduling option
  1404. // Prefer process.nextTick or MutationObserver, then check for
  1405. // setTimeout, and finally vertx, since its the only env that doesn't
  1406. // have setTimeout
  1407. var MutationObs;
  1408. var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
  1409. // Default env
  1410. var setTimer = function(f, ms) { return setTimeout(f, ms); };
  1411. var clearTimer = function(t) { return clearTimeout(t); };
  1412. var asap = function (f) { return capturedSetTimeout(f, 0); };
  1413. // Detect specific env
  1414. if (isNode()) { // Node
  1415. asap = function (f) { return process.nextTick(f); };
  1416. } else if (MutationObs = hasMutationObserver()) { // Modern browser
  1417. asap = initMutationObserver(MutationObs);
  1418. } else if (!capturedSetTimeout) { // vert.x
  1419. var vertxRequire = require;
  1420. var vertx = vertxRequire('vertx');
  1421. setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
  1422. clearTimer = vertx.cancelTimer;
  1423. asap = vertx.runOnLoop || vertx.runOnContext;
  1424. }
  1425. return {
  1426. setTimer: setTimer,
  1427. clearTimer: clearTimer,
  1428. asap: asap
  1429. };
  1430. function isNode () {
  1431. return typeof process !== 'undefined' &&
  1432. Object.prototype.toString.call(process) === '[object process]';
  1433. }
  1434. function hasMutationObserver () {
  1435. return (typeof MutationObserver === 'function' && MutationObserver) ||
  1436. (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
  1437. }
  1438. function initMutationObserver(MutationObserver) {
  1439. var scheduled;
  1440. var node = document.createTextNode('');
  1441. var o = new MutationObserver(run);
  1442. o.observe(node, { characterData: true });
  1443. function run() {
  1444. var f = scheduled;
  1445. scheduled = void 0;
  1446. f();
  1447. }
  1448. var i = 0;
  1449. return function (f) {
  1450. scheduled = f;
  1451. node.data = (i ^= 1);
  1452. };
  1453. }
  1454. });
  1455. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  1456. },{}],23:[function(require,module,exports){
  1457. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1458. /** @author Brian Cavalier */
  1459. /** @author John Hann */
  1460. (function(define) { 'use strict';
  1461. define(function() {
  1462. return {
  1463. formatError: formatError,
  1464. formatObject: formatObject,
  1465. tryStringify: tryStringify
  1466. };
  1467. /**
  1468. * Format an error into a string. If e is an Error and has a stack property,
  1469. * it's returned. Otherwise, e is formatted using formatObject, with a
  1470. * warning added about e not being a proper Error.
  1471. * @param {*} e
  1472. * @returns {String} formatted string, suitable for output to developers
  1473. */
  1474. function formatError(e) {
  1475. var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
  1476. return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
  1477. }
  1478. /**
  1479. * Format an object, detecting "plain" objects and running them through
  1480. * JSON.stringify if possible.
  1481. * @param {Object} o
  1482. * @returns {string}
  1483. */
  1484. function formatObject(o) {
  1485. var s = String(o);
  1486. if(s === '[object Object]' && typeof JSON !== 'undefined') {
  1487. s = tryStringify(o, s);
  1488. }
  1489. return s;
  1490. }
  1491. /**
  1492. * Try to return the result of JSON.stringify(x). If that fails, return
  1493. * defaultValue
  1494. * @param {*} x
  1495. * @param {*} defaultValue
  1496. * @returns {String|*} JSON.stringify(x) or defaultValue
  1497. */
  1498. function tryStringify(x, defaultValue) {
  1499. try {
  1500. return JSON.stringify(x);
  1501. } catch(e) {
  1502. return defaultValue;
  1503. }
  1504. }
  1505. });
  1506. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1507. },{}],24:[function(require,module,exports){
  1508. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1509. /** @author Brian Cavalier */
  1510. /** @author John Hann */
  1511. (function(define) { 'use strict';
  1512. define(function() {
  1513. return function liftAll(liftOne, combine, dst, src) {
  1514. if(typeof combine === 'undefined') {
  1515. combine = defaultCombine;
  1516. }
  1517. return Object.keys(src).reduce(function(dst, key) {
  1518. var f = src[key];
  1519. return typeof f === 'function' ? combine(dst, liftOne(f), key) : dst;
  1520. }, typeof dst === 'undefined' ? defaultDst(src) : dst);
  1521. };
  1522. function defaultCombine(o, f, k) {
  1523. o[k] = f;
  1524. return o;
  1525. }
  1526. function defaultDst(src) {
  1527. return typeof src === 'function' ? src.bind() : Object.create(src);
  1528. }
  1529. });
  1530. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1531. },{}],25:[function(require,module,exports){
  1532. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  1533. /** @author Brian Cavalier */
  1534. /** @author John Hann */
  1535. (function(define) { 'use strict';
  1536. define(function() {
  1537. return function makePromise(environment) {
  1538. var tasks = environment.scheduler;
  1539. var emitRejection = initEmitRejection();
  1540. var objectCreate = Object.create ||
  1541. function(proto) {
  1542. function Child() {}
  1543. Child.prototype = proto;
  1544. return new Child();
  1545. };
  1546. /**
  1547. * Create a promise whose fate is determined by resolver
  1548. * @constructor
  1549. * @returns {Promise} promise
  1550. * @name Promise
  1551. */
  1552. function Promise(resolver, handler) {
  1553. this._handler = resolver === Handler ? handler : init(resolver);
  1554. }
  1555. /**
  1556. * Run the supplied resolver
  1557. * @param resolver
  1558. * @returns {Pending}
  1559. */
  1560. function init(resolver) {
  1561. var handler = new Pending();
  1562. try {
  1563. resolver(promiseResolve, promiseReject, promiseNotify);
  1564. } catch (e) {
  1565. promiseReject(e);
  1566. }
  1567. return handler;
  1568. /**
  1569. * Transition from pre-resolution state to post-resolution state, notifying
  1570. * all listeners of the ultimate fulfillment or rejection
  1571. * @param {*} x resolution value
  1572. */
  1573. function promiseResolve (x) {
  1574. handler.resolve(x);
  1575. }
  1576. /**
  1577. * Reject this promise with reason, which will be used verbatim
  1578. * @param {Error|*} reason rejection reason, strongly suggested
  1579. * to be an Error type
  1580. */
  1581. function promiseReject (reason) {
  1582. handler.reject(reason);
  1583. }
  1584. /**
  1585. * @deprecated
  1586. * Issue a progress event, notifying all progress listeners
  1587. * @param {*} x progress event payload to pass to all listeners
  1588. */
  1589. function promiseNotify (x) {
  1590. handler.notify(x);
  1591. }
  1592. }
  1593. // Creation
  1594. Promise.resolve = resolve;
  1595. Promise.reject = reject;
  1596. Promise.never = never;
  1597. Promise._defer = defer;
  1598. Promise._handler = getHandler;
  1599. /**
  1600. * Returns a trusted promise. If x is already a trusted promise, it is
  1601. * returned, otherwise returns a new trusted Promise which follows x.
  1602. * @param {*} x
  1603. * @return {Promise} promise
  1604. */
  1605. function resolve(x) {
  1606. return isPromise(x) ? x
  1607. : new Promise(Handler, new Async(getHandler(x)));
  1608. }
  1609. /**
  1610. * Return a reject promise with x as its reason (x is used verbatim)
  1611. * @param {*} x
  1612. * @returns {Promise} rejected promise
  1613. */
  1614. function reject(x) {
  1615. return new Promise(Handler, new Async(new Rejected(x)));
  1616. }
  1617. /**
  1618. * Return a promise that remains pending forever
  1619. * @returns {Promise} forever-pending promise.
  1620. */
  1621. function never() {
  1622. return foreverPendingPromise; // Should be frozen
  1623. }
  1624. /**
  1625. * Creates an internal {promise, resolver} pair
  1626. * @private
  1627. * @returns {Promise}
  1628. */
  1629. function defer() {
  1630. return new Promise(Handler, new Pending());
  1631. }
  1632. // Transformation and flow control
  1633. /**
  1634. * Transform this promise's fulfillment value, returning a new Promise
  1635. * for the transformed result. If the promise cannot be fulfilled, onRejected
  1636. * is called with the reason. onProgress *may* be called with updates toward
  1637. * this promise's fulfillment.
  1638. * @param {function=} onFulfilled fulfillment handler
  1639. * @param {function=} onRejected rejection handler
  1640. * @param {function=} onProgress @deprecated progress handler
  1641. * @return {Promise} new promise
  1642. */
  1643. Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
  1644. var parent = this._handler;
  1645. var state = parent.join().state();
  1646. if ((typeof onFulfilled !== 'function' && state > 0) ||
  1647. (typeof onRejected !== 'function' && state < 0)) {
  1648. // Short circuit: value will not change, simply share handler
  1649. return new this.constructor(Handler, parent);
  1650. }
  1651. var p = this._beget();
  1652. var child = p._handler;
  1653. parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
  1654. return p;
  1655. };
  1656. /**
  1657. * If this promise cannot be fulfilled due to an error, call onRejected to
  1658. * handle the error. Shortcut for .then(undefined, onRejected)
  1659. * @param {function?} onRejected
  1660. * @return {Promise}
  1661. */
  1662. Promise.prototype['catch'] = function(onRejected) {
  1663. return this.then(void 0, onRejected);
  1664. };
  1665. /**
  1666. * Creates a new, pending promise of the same type as this promise
  1667. * @private
  1668. * @returns {Promise}
  1669. */
  1670. Promise.prototype._beget = function() {
  1671. return begetFrom(this._handler, this.constructor);
  1672. };
  1673. function begetFrom(parent, Promise) {
  1674. var child = new Pending(parent.receiver, parent.join().context);
  1675. return new Promise(Handler, child);
  1676. }
  1677. // Array combinators
  1678. Promise.all = all;
  1679. Promise.race = race;
  1680. Promise._traverse = traverse;
  1681. /**
  1682. * Return a promise that will fulfill when all promises in the
  1683. * input array have fulfilled, or will reject when one of the
  1684. * promises rejects.
  1685. * @param {array} promises array of promises
  1686. * @returns {Promise} promise for array of fulfillment values
  1687. */
  1688. function all(promises) {
  1689. return traverseWith(snd, null, promises);
  1690. }
  1691. /**
  1692. * Array<Promise<X>> -> Promise<Array<f(X)>>
  1693. * @private
  1694. * @param {function} f function to apply to each promise's value
  1695. * @param {Array} promises array of promises
  1696. * @returns {Promise} promise for transformed values
  1697. */
  1698. function traverse(f, promises) {
  1699. return traverseWith(tryCatch2, f, promises);
  1700. }
  1701. function traverseWith(tryMap, f, promises) {
  1702. var handler = typeof f === 'function' ? mapAt : settleAt;
  1703. var resolver = new Pending();
  1704. var pending = promises.length >>> 0;
  1705. var results = new Array(pending);
  1706. for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
  1707. x = promises[i];
  1708. if (x === void 0 && !(i in promises)) {
  1709. --pending;
  1710. continue;
  1711. }
  1712. traverseAt(promises, handler, i, x, resolver);
  1713. }
  1714. if(pending === 0) {
  1715. resolver.become(new Fulfilled(results));
  1716. }
  1717. return new Promise(Handler, resolver);
  1718. function mapAt(i, x, resolver) {
  1719. if(!resolver.resolved) {
  1720. traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
  1721. }
  1722. }
  1723. function settleAt(i, x, resolver) {
  1724. results[i] = x;
  1725. if(--pending === 0) {
  1726. resolver.become(new Fulfilled(results));
  1727. }
  1728. }
  1729. }
  1730. function traverseAt(promises, handler, i, x, resolver) {
  1731. if (maybeThenable(x)) {
  1732. var h = getHandlerMaybeThenable(x);
  1733. var s = h.state();
  1734. if (s === 0) {
  1735. h.fold(handler, i, void 0, resolver);
  1736. } else if (s > 0) {
  1737. handler(i, h.value, resolver);
  1738. } else {
  1739. resolver.become(h);
  1740. visitRemaining(promises, i+1, h);
  1741. }
  1742. } else {
  1743. handler(i, x, resolver);
  1744. }
  1745. }
  1746. Promise._visitRemaining = visitRemaining;
  1747. function visitRemaining(promises, start, handler) {
  1748. for(var i=start; i<promises.length; ++i) {
  1749. markAsHandled(getHandler(promises[i]), handler);
  1750. }
  1751. }
  1752. function markAsHandled(h, handler) {
  1753. if(h === handler) {
  1754. return;
  1755. }
  1756. var s = h.state();
  1757. if(s === 0) {
  1758. h.visit(h, void 0, h._unreport);
  1759. } else if(s < 0) {
  1760. h._unreport();
  1761. }
  1762. }
  1763. /**
  1764. * Fulfill-reject competitive race. Return a promise that will settle
  1765. * to the same state as the earliest input promise to settle.
  1766. *
  1767. * WARNING: The ES6 Promise spec requires that race()ing an empty array
  1768. * must return a promise that is pending forever. This implementation
  1769. * returns a singleton forever-pending promise, the same singleton that is
  1770. * returned by Promise.never(), thus can be checked with ===
  1771. *
  1772. * @param {array} promises array of promises to race
  1773. * @returns {Promise} if input is non-empty, a promise that will settle
  1774. * to the same outcome as the earliest input promise to settle. if empty
  1775. * is empty, returns a promise that will never settle.
  1776. */
  1777. function race(promises) {
  1778. if(typeof promises !== 'object' || promises === null) {
  1779. return reject(new TypeError('non-iterable passed to race()'));
  1780. }
  1781. // Sigh, race([]) is untestable unless we return *something*
  1782. // that is recognizable without calling .then() on it.
  1783. return promises.length === 0 ? never()
  1784. : promises.length === 1 ? resolve(promises[0])
  1785. : runRace(promises);
  1786. }
  1787. function runRace(promises) {
  1788. var resolver = new Pending();
  1789. var i, x, h;
  1790. for(i=0; i<promises.length; ++i) {
  1791. x = promises[i];
  1792. if (x === void 0 && !(i in promises)) {
  1793. continue;
  1794. }
  1795. h = getHandler(x);
  1796. if(h.state() !== 0) {
  1797. resolver.become(h);
  1798. visitRemaining(promises, i+1, h);
  1799. break;
  1800. } else {
  1801. h.visit(resolver, resolver.resolve, resolver.reject);
  1802. }
  1803. }
  1804. return new Promise(Handler, resolver);
  1805. }
  1806. // Promise internals
  1807. // Below this, everything is @private
  1808. /**
  1809. * Get an appropriate handler for x, without checking for cycles
  1810. * @param {*} x
  1811. * @returns {object} handler
  1812. */
  1813. function getHandler(x) {
  1814. if(isPromise(x)) {
  1815. return x._handler.join();
  1816. }
  1817. return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
  1818. }
  1819. /**
  1820. * Get a handler for thenable x.
  1821. * NOTE: You must only call this if maybeThenable(x) == true
  1822. * @param {object|function|Promise} x
  1823. * @returns {object} handler
  1824. */
  1825. function getHandlerMaybeThenable(x) {
  1826. return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
  1827. }
  1828. /**
  1829. * Get a handler for potentially untrusted thenable x
  1830. * @param {*} x
  1831. * @returns {object} handler
  1832. */
  1833. function getHandlerUntrusted(x) {
  1834. try {
  1835. var untrustedThen = x.then;
  1836. return typeof untrustedThen === 'function'
  1837. ? new Thenable(untrustedThen, x)
  1838. : new Fulfilled(x);
  1839. } catch(e) {
  1840. return new Rejected(e);
  1841. }
  1842. }
  1843. /**
  1844. * Handler for a promise that is pending forever
  1845. * @constructor
  1846. */
  1847. function Handler() {}
  1848. Handler.prototype.when
  1849. = Handler.prototype.become
  1850. = Handler.prototype.notify // deprecated
  1851. = Handler.prototype.fail
  1852. = Handler.prototype._unreport
  1853. = Handler.prototype._report
  1854. = noop;
  1855. Handler.prototype._state = 0;
  1856. Handler.prototype.state = function() {
  1857. return this._state;
  1858. };
  1859. /**
  1860. * Recursively collapse handler chain to find the handler
  1861. * nearest to the fully resolved value.
  1862. * @returns {object} handler nearest the fully resolved value
  1863. */
  1864. Handler.prototype.join = function() {
  1865. var h = this;
  1866. while(h.handler !== void 0) {
  1867. h = h.handler;
  1868. }
  1869. return h;
  1870. };
  1871. Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
  1872. this.when({
  1873. resolver: to,
  1874. receiver: receiver,
  1875. fulfilled: fulfilled,
  1876. rejected: rejected,
  1877. progress: progress
  1878. });
  1879. };
  1880. Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
  1881. this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
  1882. };
  1883. Handler.prototype.fold = function(f, z, c, to) {
  1884. this.when(new Fold(f, z, c, to));
  1885. };
  1886. /**
  1887. * Handler that invokes fail() on any handler it becomes
  1888. * @constructor
  1889. */
  1890. function FailIfRejected() {}
  1891. inherit(Handler, FailIfRejected);
  1892. FailIfRejected.prototype.become = function(h) {
  1893. h.fail();
  1894. };
  1895. var failIfRejected = new FailIfRejected();
  1896. /**
  1897. * Handler that manages a queue of consumers waiting on a pending promise
  1898. * @constructor
  1899. */
  1900. function Pending(receiver, inheritedContext) {
  1901. Promise.createContext(this, inheritedContext);
  1902. this.consumers = void 0;
  1903. this.receiver = receiver;
  1904. this.handler = void 0;
  1905. this.resolved = false;
  1906. }
  1907. inherit(Handler, Pending);
  1908. Pending.prototype._state = 0;
  1909. Pending.prototype.resolve = function(x) {
  1910. this.become(getHandler(x));
  1911. };
  1912. Pending.prototype.reject = function(x) {
  1913. if(this.resolved) {
  1914. return;
  1915. }
  1916. this.become(new Rejected(x));
  1917. };
  1918. Pending.prototype.join = function() {
  1919. if (!this.resolved) {
  1920. return this;
  1921. }
  1922. var h = this;
  1923. while (h.handler !== void 0) {
  1924. h = h.handler;
  1925. if (h === this) {
  1926. return this.handler = cycle();
  1927. }
  1928. }
  1929. return h;
  1930. };
  1931. Pending.prototype.run = function() {
  1932. var q = this.consumers;
  1933. var handler = this.handler;
  1934. this.handler = this.handler.join();
  1935. this.consumers = void 0;
  1936. for (var i = 0; i < q.length; ++i) {
  1937. handler.when(q[i]);
  1938. }
  1939. };
  1940. Pending.prototype.become = function(handler) {
  1941. if(this.resolved) {
  1942. return;
  1943. }
  1944. this.resolved = true;
  1945. this.handler = handler;
  1946. if(this.consumers !== void 0) {
  1947. tasks.enqueue(this);
  1948. }
  1949. if(this.context !== void 0) {
  1950. handler._report(this.context);
  1951. }
  1952. };
  1953. Pending.prototype.when = function(continuation) {
  1954. if(this.resolved) {
  1955. tasks.enqueue(new ContinuationTask(continuation, this.handler));
  1956. } else {
  1957. if(this.consumers === void 0) {
  1958. this.consumers = [continuation];
  1959. } else {
  1960. this.consumers.push(continuation);
  1961. }
  1962. }
  1963. };
  1964. /**
  1965. * @deprecated
  1966. */
  1967. Pending.prototype.notify = function(x) {
  1968. if(!this.resolved) {
  1969. tasks.enqueue(new ProgressTask(x, this));
  1970. }
  1971. };
  1972. Pending.prototype.fail = function(context) {
  1973. var c = typeof context === 'undefined' ? this.context : context;
  1974. this.resolved && this.handler.join().fail(c);
  1975. };
  1976. Pending.prototype._report = function(context) {
  1977. this.resolved && this.handler.join()._report(context);
  1978. };
  1979. Pending.prototype._unreport = function() {
  1980. this.resolved && this.handler.join()._unreport();
  1981. };
  1982. /**
  1983. * Wrap another handler and force it into a future stack
  1984. * @param {object} handler
  1985. * @constructor
  1986. */
  1987. function Async(handler) {
  1988. this.handler = handler;
  1989. }
  1990. inherit(Handler, Async);
  1991. Async.prototype.when = function(continuation) {
  1992. tasks.enqueue(new ContinuationTask(continuation, this));
  1993. };
  1994. Async.prototype._report = function(context) {
  1995. this.join()._report(context);
  1996. };
  1997. Async.prototype._unreport = function() {
  1998. this.join()._unreport();
  1999. };
  2000. /**
  2001. * Handler that wraps an untrusted thenable and assimilates it in a future stack
  2002. * @param {function} then
  2003. * @param {{then: function}} thenable
  2004. * @constructor
  2005. */
  2006. function Thenable(then, thenable) {
  2007. Pending.call(this);
  2008. tasks.enqueue(new AssimilateTask(then, thenable, this));
  2009. }
  2010. inherit(Pending, Thenable);
  2011. /**
  2012. * Handler for a fulfilled promise
  2013. * @param {*} x fulfillment value
  2014. * @constructor
  2015. */
  2016. function Fulfilled(x) {
  2017. Promise.createContext(this);
  2018. this.value = x;
  2019. }
  2020. inherit(Handler, Fulfilled);
  2021. Fulfilled.prototype._state = 1;
  2022. Fulfilled.prototype.fold = function(f, z, c, to) {
  2023. runContinuation3(f, z, this, c, to);
  2024. };
  2025. Fulfilled.prototype.when = function(cont) {
  2026. runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
  2027. };
  2028. var errorId = 0;
  2029. /**
  2030. * Handler for a rejected promise
  2031. * @param {*} x rejection reason
  2032. * @constructor
  2033. */
  2034. function Rejected(x) {
  2035. Promise.createContext(this);
  2036. this.id = ++errorId;
  2037. this.value = x;
  2038. this.handled = false;
  2039. this.reported = false;
  2040. this._report();
  2041. }
  2042. inherit(Handler, Rejected);
  2043. Rejected.prototype._state = -1;
  2044. Rejected.prototype.fold = function(f, z, c, to) {
  2045. to.become(this);
  2046. };
  2047. Rejected.prototype.when = function(cont) {
  2048. if(typeof cont.rejected === 'function') {
  2049. this._unreport();
  2050. }
  2051. runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
  2052. };
  2053. Rejected.prototype._report = function(context) {
  2054. tasks.afterQueue(new ReportTask(this, context));
  2055. };
  2056. Rejected.prototype._unreport = function() {
  2057. if(this.handled) {
  2058. return;
  2059. }
  2060. this.handled = true;
  2061. tasks.afterQueue(new UnreportTask(this));
  2062. };
  2063. Rejected.prototype.fail = function(context) {
  2064. this.reported = true;
  2065. emitRejection('unhandledRejection', this);
  2066. Promise.onFatalRejection(this, context === void 0 ? this.context : context);
  2067. };
  2068. function ReportTask(rejection, context) {
  2069. this.rejection = rejection;
  2070. this.context = context;
  2071. }
  2072. ReportTask.prototype.run = function() {
  2073. if(!this.rejection.handled && !this.rejection.reported) {
  2074. this.rejection.reported = true;
  2075. emitRejection('unhandledRejection', this.rejection) ||
  2076. Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
  2077. }
  2078. };
  2079. function UnreportTask(rejection) {
  2080. this.rejection = rejection;
  2081. }
  2082. UnreportTask.prototype.run = function() {
  2083. if(this.rejection.reported) {
  2084. emitRejection('rejectionHandled', this.rejection) ||
  2085. Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
  2086. }
  2087. };
  2088. // Unhandled rejection hooks
  2089. // By default, everything is a noop
  2090. Promise.createContext
  2091. = Promise.enterContext
  2092. = Promise.exitContext
  2093. = Promise.onPotentiallyUnhandledRejection
  2094. = Promise.onPotentiallyUnhandledRejectionHandled
  2095. = Promise.onFatalRejection
  2096. = noop;
  2097. // Errors and singletons
  2098. var foreverPendingHandler = new Handler();
  2099. var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
  2100. function cycle() {
  2101. return new Rejected(new TypeError('Promise cycle'));
  2102. }
  2103. // Task runners
  2104. /**
  2105. * Run a single consumer
  2106. * @constructor
  2107. */
  2108. function ContinuationTask(continuation, handler) {
  2109. this.continuation = continuation;
  2110. this.handler = handler;
  2111. }
  2112. ContinuationTask.prototype.run = function() {
  2113. this.handler.join().when(this.continuation);
  2114. };
  2115. /**
  2116. * Run a queue of progress handlers
  2117. * @constructor
  2118. */
  2119. function ProgressTask(value, handler) {
  2120. this.handler = handler;
  2121. this.value = value;
  2122. }
  2123. ProgressTask.prototype.run = function() {
  2124. var q = this.handler.consumers;
  2125. if(q === void 0) {
  2126. return;
  2127. }
  2128. for (var c, i = 0; i < q.length; ++i) {
  2129. c = q[i];
  2130. runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
  2131. }
  2132. };
  2133. /**
  2134. * Assimilate a thenable, sending it's value to resolver
  2135. * @param {function} then
  2136. * @param {object|function} thenable
  2137. * @param {object} resolver
  2138. * @constructor
  2139. */
  2140. function AssimilateTask(then, thenable, resolver) {
  2141. this._then = then;
  2142. this.thenable = thenable;
  2143. this.resolver = resolver;
  2144. }
  2145. AssimilateTask.prototype.run = function() {
  2146. var h = this.resolver;
  2147. tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
  2148. function _resolve(x) { h.resolve(x); }
  2149. function _reject(x) { h.reject(x); }
  2150. function _notify(x) { h.notify(x); }
  2151. };
  2152. function tryAssimilate(then, thenable, resolve, reject, notify) {
  2153. try {
  2154. then.call(thenable, resolve, reject, notify);
  2155. } catch (e) {
  2156. reject(e);
  2157. }
  2158. }
  2159. /**
  2160. * Fold a handler value with z
  2161. * @constructor
  2162. */
  2163. function Fold(f, z, c, to) {
  2164. this.f = f; this.z = z; this.c = c; this.to = to;
  2165. this.resolver = failIfRejected;
  2166. this.receiver = this;
  2167. }
  2168. Fold.prototype.fulfilled = function(x) {
  2169. this.f.call(this.c, this.z, x, this.to);
  2170. };
  2171. Fold.prototype.rejected = function(x) {
  2172. this.to.reject(x);
  2173. };
  2174. Fold.prototype.progress = function(x) {
  2175. this.to.notify(x);
  2176. };
  2177. // Other helpers
  2178. /**
  2179. * @param {*} x
  2180. * @returns {boolean} true iff x is a trusted Promise
  2181. */
  2182. function isPromise(x) {
  2183. return x instanceof Promise;
  2184. }
  2185. /**
  2186. * Test just enough to rule out primitives, in order to take faster
  2187. * paths in some code
  2188. * @param {*} x
  2189. * @returns {boolean} false iff x is guaranteed *not* to be a thenable
  2190. */
  2191. function maybeThenable(x) {
  2192. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  2193. }
  2194. function runContinuation1(f, h, receiver, next) {
  2195. if(typeof f !== 'function') {
  2196. return next.become(h);
  2197. }
  2198. Promise.enterContext(h);
  2199. tryCatchReject(f, h.value, receiver, next);
  2200. Promise.exitContext();
  2201. }
  2202. function runContinuation3(f, x, h, receiver, next) {
  2203. if(typeof f !== 'function') {
  2204. return next.become(h);
  2205. }
  2206. Promise.enterContext(h);
  2207. tryCatchReject3(f, x, h.value, receiver, next);
  2208. Promise.exitContext();
  2209. }
  2210. /**
  2211. * @deprecated
  2212. */
  2213. function runNotify(f, x, h, receiver, next) {
  2214. if(typeof f !== 'function') {
  2215. return next.notify(x);
  2216. }
  2217. Promise.enterContext(h);
  2218. tryCatchReturn(f, x, receiver, next);
  2219. Promise.exitContext();
  2220. }
  2221. function tryCatch2(f, a, b) {
  2222. try {
  2223. return f(a, b);
  2224. } catch(e) {
  2225. return reject(e);
  2226. }
  2227. }
  2228. /**
  2229. * Return f.call(thisArg, x), or if it throws return a rejected promise for
  2230. * the thrown exception
  2231. */
  2232. function tryCatchReject(f, x, thisArg, next) {
  2233. try {
  2234. next.become(getHandler(f.call(thisArg, x)));
  2235. } catch(e) {
  2236. next.become(new Rejected(e));
  2237. }
  2238. }
  2239. /**
  2240. * Same as above, but includes the extra argument parameter.
  2241. */
  2242. function tryCatchReject3(f, x, y, thisArg, next) {
  2243. try {
  2244. f.call(thisArg, x, y, next);
  2245. } catch(e) {
  2246. next.become(new Rejected(e));
  2247. }
  2248. }
  2249. /**
  2250. * @deprecated
  2251. * Return f.call(thisArg, x), or if it throws, *return* the exception
  2252. */
  2253. function tryCatchReturn(f, x, thisArg, next) {
  2254. try {
  2255. next.notify(f.call(thisArg, x));
  2256. } catch(e) {
  2257. next.notify(e);
  2258. }
  2259. }
  2260. function inherit(Parent, Child) {
  2261. Child.prototype = objectCreate(Parent.prototype);
  2262. Child.prototype.constructor = Child;
  2263. }
  2264. function snd(x, y) {
  2265. return y;
  2266. }
  2267. function noop() {}
  2268. function initEmitRejection() {
  2269. /*global process, self, CustomEvent*/
  2270. if(typeof process !== 'undefined' && process !== null
  2271. && typeof process.emit === 'function') {
  2272. // Returning falsy here means to call the default
  2273. // onPotentiallyUnhandledRejection API. This is safe even in
  2274. // browserify since process.emit always returns falsy in browserify:
  2275. // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
  2276. return function(type, rejection) {
  2277. return type === 'unhandledRejection'
  2278. ? process.emit(type, rejection.value, rejection)
  2279. : process.emit(type, rejection);
  2280. };
  2281. } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') {
  2282. return (function(noop, self, CustomEvent) {
  2283. var hasCustomEvent = false;
  2284. try {
  2285. var ev = new CustomEvent('unhandledRejection');
  2286. hasCustomEvent = ev instanceof CustomEvent;
  2287. } catch (e) {}
  2288. return !hasCustomEvent ? noop : function(type, rejection) {
  2289. var ev = new CustomEvent(type, {
  2290. detail: {
  2291. reason: rejection.value,
  2292. key: rejection
  2293. },
  2294. bubbles: false,
  2295. cancelable: true
  2296. });
  2297. return !self.dispatchEvent(ev);
  2298. };
  2299. }(noop, self, CustomEvent));
  2300. }
  2301. return noop;
  2302. }
  2303. return Promise;
  2304. };
  2305. });
  2306. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  2307. },{}],26:[function(require,module,exports){
  2308. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2309. /** @author Brian Cavalier */
  2310. /** @author John Hann */
  2311. (function(define) { 'use strict';
  2312. define(function() {
  2313. return {
  2314. pending: toPendingState,
  2315. fulfilled: toFulfilledState,
  2316. rejected: toRejectedState,
  2317. inspect: inspect
  2318. };
  2319. function toPendingState() {
  2320. return { state: 'pending' };
  2321. }
  2322. function toRejectedState(e) {
  2323. return { state: 'rejected', reason: e };
  2324. }
  2325. function toFulfilledState(x) {
  2326. return { state: 'fulfilled', value: x };
  2327. }
  2328. function inspect(handler) {
  2329. var state = handler.state();
  2330. return state === 0 ? toPendingState()
  2331. : state > 0 ? toFulfilledState(handler.value)
  2332. : toRejectedState(handler.value);
  2333. }
  2334. });
  2335. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  2336. },{}],27:[function(require,module,exports){
  2337. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2338. /** @author Brian Cavalier */
  2339. /** @author John Hann */
  2340. (function(define) { 'use strict';
  2341. define(function(require) {
  2342. var PromiseMonitor = require('./monitor/PromiseMonitor');
  2343. var ConsoleReporter = require('./monitor/ConsoleReporter');
  2344. var promiseMonitor = new PromiseMonitor(new ConsoleReporter());
  2345. return function(Promise) {
  2346. return promiseMonitor.monitor(Promise);
  2347. };
  2348. });
  2349. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  2350. },{"./monitor/ConsoleReporter":28,"./monitor/PromiseMonitor":29}],28:[function(require,module,exports){
  2351. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2352. /** @author Brian Cavalier */
  2353. /** @author John Hann */
  2354. (function(define) { 'use strict';
  2355. define(function(require) {
  2356. var error = require('./error');
  2357. var unhandledRejectionsMsg = '[promises] Unhandled rejections: ';
  2358. var allHandledMsg = '[promises] All previously unhandled rejections have now been handled';
  2359. function ConsoleReporter() {
  2360. this._previouslyReported = false;
  2361. }
  2362. ConsoleReporter.prototype = initDefaultLogging();
  2363. ConsoleReporter.prototype.log = function(traces) {
  2364. if(traces.length === 0) {
  2365. if(this._previouslyReported) {
  2366. this._previouslyReported = false;
  2367. this.msg(allHandledMsg);
  2368. }
  2369. return;
  2370. }
  2371. this._previouslyReported = true;
  2372. this.groupStart(unhandledRejectionsMsg + traces.length);
  2373. try {
  2374. this._log(traces);
  2375. } finally {
  2376. this.groupEnd();
  2377. }
  2378. };
  2379. ConsoleReporter.prototype._log = function(traces) {
  2380. for(var i=0; i<traces.length; ++i) {
  2381. this.warn(error.format(traces[i]));
  2382. }
  2383. };
  2384. function initDefaultLogging() {
  2385. /*jshint maxcomplexity:7*/
  2386. var log, warn, groupStart, groupEnd;
  2387. if(typeof console === 'undefined') {
  2388. log = warn = consoleNotAvailable;
  2389. } else {
  2390. // Alias console to prevent things like uglify's drop_console option from
  2391. // removing console.log/error. Unhandled rejections fall into the same
  2392. // category as uncaught exceptions, and build tools shouldn't silence them.
  2393. var localConsole = console;
  2394. if(typeof localConsole.error === 'function'
  2395. && typeof localConsole.dir === 'function') {
  2396. warn = function(s) {
  2397. localConsole.error(s);
  2398. };
  2399. log = function(s) {
  2400. localConsole.log(s);
  2401. };
  2402. if(typeof localConsole.groupCollapsed === 'function') {
  2403. groupStart = function(s) {
  2404. localConsole.groupCollapsed(s);
  2405. };
  2406. groupEnd = function() {
  2407. localConsole.groupEnd();
  2408. };
  2409. }
  2410. } else {
  2411. // IE8 has console.log and JSON, so we can make a
  2412. // reasonably useful warn() from those.
  2413. // Credit to webpro (https://github.com/webpro) for this idea
  2414. // typeof localConsole.log will return 'object' in IE8, so can't test it with === 'function'
  2415. // Since this is more of a corner case for IE8, I'm ok to check it with !== 'undefined' to reduce complexity
  2416. if (typeof localConsole.log !== 'undefined' && typeof JSON !== 'undefined') {
  2417. log = warn = function(x) {
  2418. if (typeof x !== 'string') {
  2419. try {
  2420. x = JSON.stringify(x);
  2421. } catch (e) {
  2422. }
  2423. }
  2424. localConsole.log(x);
  2425. };
  2426. } else {
  2427. log = warn = consoleNotAvailable;
  2428. }
  2429. }
  2430. }
  2431. return {
  2432. msg: log,
  2433. warn: warn,
  2434. groupStart: groupStart || warn,
  2435. groupEnd: groupEnd || consoleNotAvailable
  2436. };
  2437. }
  2438. function consoleNotAvailable() {}
  2439. return ConsoleReporter;
  2440. });
  2441. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  2442. },{"./error":31}],29:[function(require,module,exports){
  2443. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2444. /** @author Brian Cavalier */
  2445. /** @author John Hann */
  2446. (function(define) { 'use strict';
  2447. define(function(require) {
  2448. var defaultStackJumpSeparator = 'from execution context:';
  2449. 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;
  2450. var setTimer = require('../lib/env').setTimer;
  2451. var error = require('./error');
  2452. var executionContext = [];
  2453. function PromiseMonitor(reporter) {
  2454. this.logDelay = 0;
  2455. this.stackFilter = defaultStackFilter;
  2456. this.stackJumpSeparator = defaultStackJumpSeparator;
  2457. this.filterDuplicateFrames = true;
  2458. this._reporter = reporter;
  2459. if(typeof reporter.configurePromiseMonitor === 'function') {
  2460. reporter.configurePromiseMonitor(this);
  2461. }
  2462. this._traces = [];
  2463. this._traceTask = 0;
  2464. var self = this;
  2465. this._doLogTraces = function() {
  2466. self._logTraces();
  2467. };
  2468. }
  2469. PromiseMonitor.prototype.monitor = function(Promise) {
  2470. var self = this;
  2471. Promise.createContext = function(p, context) {
  2472. p.context = self.createContext(p, context);
  2473. };
  2474. Promise.enterContext = function(p) {
  2475. executionContext.push(p.context);
  2476. };
  2477. Promise.exitContext = function() {
  2478. executionContext.pop();
  2479. };
  2480. Promise.onPotentiallyUnhandledRejection = function(rejection, extraContext) {
  2481. return self.addTrace(rejection, extraContext);
  2482. };
  2483. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  2484. return self.removeTrace(rejection);
  2485. };
  2486. Promise.onFatalRejection = function(rejection, extraContext) {
  2487. return self.fatal(rejection, extraContext);
  2488. };
  2489. return this;
  2490. };
  2491. PromiseMonitor.prototype.createContext = function(at, parentContext) {
  2492. var context = {
  2493. parent: parentContext || executionContext[executionContext.length - 1],
  2494. stack: void 0
  2495. };
  2496. error.captureStack(context, at.constructor);
  2497. return context;
  2498. };
  2499. PromiseMonitor.prototype.addTrace = function(handler, extraContext) {
  2500. var t, i;
  2501. for(i = this._traces.length-1; i >= 0; --i) {
  2502. t = this._traces[i];
  2503. if(t.handler === handler) {
  2504. break;
  2505. }
  2506. }
  2507. if(i >= 0) {
  2508. t.extraContext = extraContext;
  2509. } else {
  2510. this._traces.push({
  2511. handler: handler,
  2512. extraContext: extraContext
  2513. });
  2514. }
  2515. this.logTraces();
  2516. };
  2517. PromiseMonitor.prototype.removeTrace = function(/*handler*/) {
  2518. this.logTraces();
  2519. };
  2520. PromiseMonitor.prototype.fatal = function(handler, extraContext) {
  2521. var err = new Error();
  2522. err.stack = this._createLongTrace(handler.value, handler.context, extraContext).join('\n');
  2523. setTimer(function() {
  2524. throw err;
  2525. }, 0);
  2526. };
  2527. PromiseMonitor.prototype.logTraces = function() {
  2528. if(!this._traceTask) {
  2529. this._traceTask = setTimer(this._doLogTraces, this.logDelay);
  2530. }
  2531. };
  2532. PromiseMonitor.prototype._logTraces = function() {
  2533. this._traceTask = void 0;
  2534. this._traces = this._traces.filter(filterHandled);
  2535. this._reporter.log(this.formatTraces(this._traces));
  2536. };
  2537. PromiseMonitor.prototype.formatTraces = function(traces) {
  2538. return traces.map(function(t) {
  2539. return this._createLongTrace(t.handler.value, t.handler.context, t.extraContext);
  2540. }, this);
  2541. };
  2542. PromiseMonitor.prototype._createLongTrace = function(e, context, extraContext) {
  2543. var trace = error.parse(e) || [String(e) + ' (WARNING: non-Error used)'];
  2544. trace = filterFrames(this.stackFilter, trace, 0);
  2545. this._appendContext(trace, context);
  2546. this._appendContext(trace, extraContext);
  2547. return this.filterDuplicateFrames ? this._removeDuplicates(trace) : trace;
  2548. };
  2549. PromiseMonitor.prototype._removeDuplicates = function(trace) {
  2550. var seen = {};
  2551. var sep = this.stackJumpSeparator;
  2552. var count = 0;
  2553. return trace.reduceRight(function(deduped, line, i) {
  2554. if(i === 0) {
  2555. deduped.unshift(line);
  2556. } else if(line === sep) {
  2557. if(count > 0) {
  2558. deduped.unshift(line);
  2559. count = 0;
  2560. }
  2561. } else if(!seen[line]) {
  2562. seen[line] = true;
  2563. deduped.unshift(line);
  2564. ++count;
  2565. }
  2566. return deduped;
  2567. }, []);
  2568. };
  2569. PromiseMonitor.prototype._appendContext = function(trace, context) {
  2570. trace.push.apply(trace, this._createTrace(context));
  2571. };
  2572. PromiseMonitor.prototype._createTrace = function(traceChain) {
  2573. var trace = [];
  2574. var stack;
  2575. while(traceChain) {
  2576. stack = error.parse(traceChain);
  2577. if (stack) {
  2578. stack = filterFrames(this.stackFilter, stack);
  2579. appendStack(trace, stack, this.stackJumpSeparator);
  2580. }
  2581. traceChain = traceChain.parent;
  2582. }
  2583. return trace;
  2584. };
  2585. function appendStack(trace, stack, separator) {
  2586. if (stack.length > 1) {
  2587. stack[0] = separator;
  2588. trace.push.apply(trace, stack);
  2589. }
  2590. }
  2591. function filterFrames(stackFilter, stack) {
  2592. return stack.filter(function(frame) {
  2593. return !stackFilter.test(frame);
  2594. });
  2595. }
  2596. function filterHandled(t) {
  2597. return !t.handler.handled;
  2598. }
  2599. return PromiseMonitor;
  2600. });
  2601. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  2602. },{"../lib/env":22,"./error":31}],30:[function(require,module,exports){
  2603. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2604. /** @author Brian Cavalier */
  2605. /** @author John Hann */
  2606. (function(define) { 'use strict';
  2607. define(function(require) {
  2608. var monitor = require('../monitor');
  2609. var Promise = require('../when').Promise;
  2610. return monitor(Promise);
  2611. });
  2612. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  2613. },{"../monitor":27,"../when":38}],31:[function(require,module,exports){
  2614. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2615. /** @author Brian Cavalier */
  2616. /** @author John Hann */
  2617. (function(define) { 'use strict';
  2618. define(function() {
  2619. var parse, captureStack, format;
  2620. if(Error.captureStackTrace) {
  2621. // Use Error.captureStackTrace if available
  2622. parse = function(e) {
  2623. return e && e.stack && e.stack.split('\n');
  2624. };
  2625. format = formatAsString;
  2626. captureStack = Error.captureStackTrace;
  2627. } else {
  2628. // Otherwise, do minimal feature detection to determine
  2629. // how to capture and format reasonable stacks.
  2630. parse = function(e) {
  2631. var stack = e && e.stack && e.stack.split('\n');
  2632. if(stack && e.message) {
  2633. stack.unshift(e.message);
  2634. }
  2635. return stack;
  2636. };
  2637. (function() {
  2638. var e = new Error();
  2639. if(typeof e.stack !== 'string') {
  2640. format = formatAsString;
  2641. captureStack = captureSpiderMonkeyStack;
  2642. } else {
  2643. format = formatAsErrorWithStack;
  2644. captureStack = useStackDirectly;
  2645. }
  2646. }());
  2647. }
  2648. function captureSpiderMonkeyStack(host) {
  2649. try {
  2650. throw new Error();
  2651. } catch(err) {
  2652. host.stack = err.stack;
  2653. }
  2654. }
  2655. function useStackDirectly(host) {
  2656. host.stack = new Error().stack;
  2657. }
  2658. function formatAsString(longTrace) {
  2659. return join(longTrace);
  2660. }
  2661. function formatAsErrorWithStack(longTrace) {
  2662. var e = new Error();
  2663. e.stack = formatAsString(longTrace);
  2664. return e;
  2665. }
  2666. // About 5-10x faster than String.prototype.join o_O
  2667. function join(a) {
  2668. var sep = false;
  2669. var s = '';
  2670. for(var i=0; i< a.length; ++i) {
  2671. if(sep) {
  2672. s += '\n' + a[i];
  2673. } else {
  2674. s+= a[i];
  2675. sep = true;
  2676. }
  2677. }
  2678. return s;
  2679. }
  2680. return {
  2681. parse: parse,
  2682. format: format,
  2683. captureStack: captureStack
  2684. };
  2685. });
  2686. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  2687. },{}],32:[function(require,module,exports){
  2688. /** @license MIT License (c) copyright 2013 original author or authors */
  2689. /**
  2690. * Collection of helpers for interfacing with node-style asynchronous functions
  2691. * using promises.
  2692. *
  2693. * @author Brian Cavalier
  2694. * @contributor Renato Zannon
  2695. */
  2696. (function(define) {
  2697. define(function(require) {
  2698. var when = require('./when');
  2699. var _liftAll = require('./lib/liftAll');
  2700. var setTimer = require('./lib/env').setTimer;
  2701. var slice = Array.prototype.slice;
  2702. var _apply = require('./lib/apply')(when.Promise, dispatch);
  2703. return {
  2704. lift: lift,
  2705. liftAll: liftAll,
  2706. apply: apply,
  2707. call: call,
  2708. createCallback: createCallback,
  2709. bindCallback: bindCallback,
  2710. liftCallback: liftCallback
  2711. };
  2712. /**
  2713. * Takes a node-style async function and calls it immediately (with an optional
  2714. * array of arguments or promises for arguments). It returns a promise whose
  2715. * resolution depends on whether the async functions calls its callback with the
  2716. * conventional error argument or not.
  2717. *
  2718. * With this it becomes possible to leverage existing APIs while still reaping
  2719. * the benefits of promises.
  2720. *
  2721. * @example
  2722. * function onlySmallNumbers(n, callback) {
  2723. * if(n < 10) {
  2724. * callback(null, n + 10);
  2725. * } else {
  2726. * callback(new Error("Calculation failed"));
  2727. * }
  2728. * }
  2729. *
  2730. * var nodefn = require("when/node/function");
  2731. *
  2732. * // Logs '15'
  2733. * nodefn.apply(onlySmallNumbers, [5]).then(console.log, console.error);
  2734. *
  2735. * // Logs 'Calculation failed'
  2736. * nodefn.apply(onlySmallNumbers, [15]).then(console.log, console.error);
  2737. *
  2738. * @param {function} f node-style function that will be called
  2739. * @param {Array} [args] array of arguments to func
  2740. * @returns {Promise} promise for the value func passes to its callback
  2741. */
  2742. function apply(f, args) {
  2743. return _apply(f, this, args || []);
  2744. }
  2745. function dispatch(f, thisArg, args, h) {
  2746. var cb = createCallback(h);
  2747. try {
  2748. switch(args.length) {
  2749. case 2: f.call(thisArg, args[0], args[1], cb); break;
  2750. case 1: f.call(thisArg, args[0], cb); break;
  2751. case 0: f.call(thisArg, cb); break;
  2752. default:
  2753. args.push(cb);
  2754. f.apply(thisArg, args);
  2755. }
  2756. } catch(e) {
  2757. h.reject(e);
  2758. }
  2759. }
  2760. /**
  2761. * Has the same behavior that {@link apply} has, with the difference that the
  2762. * arguments to the function are provided individually, while {@link apply} accepts
  2763. * a single array.
  2764. *
  2765. * @example
  2766. * function sumSmallNumbers(x, y, callback) {
  2767. * var result = x + y;
  2768. * if(result < 10) {
  2769. * callback(null, result);
  2770. * } else {
  2771. * callback(new Error("Calculation failed"));
  2772. * }
  2773. * }
  2774. *
  2775. * // Logs '5'
  2776. * nodefn.call(sumSmallNumbers, 2, 3).then(console.log, console.error);
  2777. *
  2778. * // Logs 'Calculation failed'
  2779. * nodefn.call(sumSmallNumbers, 5, 10).then(console.log, console.error);
  2780. *
  2781. * @param {function} f node-style function that will be called
  2782. * @param {...*} [args] arguments that will be forwarded to the function
  2783. * @returns {Promise} promise for the value func passes to its callback
  2784. */
  2785. function call(f /*, args... */) {
  2786. return _apply(f, this, slice.call(arguments, 1));
  2787. }
  2788. /**
  2789. * Takes a node-style function and returns new function that wraps the
  2790. * original and, instead of taking a callback, returns a promise. Also, it
  2791. * knows how to handle promises given as arguments, waiting for their
  2792. * resolution before executing.
  2793. *
  2794. * Upon execution, the orginal function is executed as well. If it passes
  2795. * a truthy value as the first argument to the callback, it will be
  2796. * interpreted as an error condition, and the promise will be rejected
  2797. * with it. Otherwise, the call is considered a resolution, and the promise
  2798. * is resolved with the callback's second argument.
  2799. *
  2800. * @example
  2801. * var fs = require("fs"), nodefn = require("when/node/function");
  2802. *
  2803. * var promiseRead = nodefn.lift(fs.readFile);
  2804. *
  2805. * // The promise is resolved with the contents of the file if everything
  2806. * // goes ok
  2807. * promiseRead('exists.txt').then(console.log, console.error);
  2808. *
  2809. * // And will be rejected if something doesn't work out
  2810. * // (e.g. the files does not exist)
  2811. * promiseRead('doesnt_exist.txt').then(console.log, console.error);
  2812. *
  2813. *
  2814. * @param {Function} f node-style function to be lifted
  2815. * @param {...*} [args] arguments to be prepended for the new function @deprecated
  2816. * @returns {Function} a promise-returning function
  2817. */
  2818. function lift(f /*, args... */) {
  2819. var args1 = arguments.length > 1 ? slice.call(arguments, 1) : [];
  2820. return function() {
  2821. // TODO: Simplify once partialing has been removed
  2822. var l = args1.length;
  2823. var al = arguments.length;
  2824. var args = new Array(al + l);
  2825. var i;
  2826. for(i=0; i<l; ++i) {
  2827. args[i] = args1[i];
  2828. }
  2829. for(i=0; i<al; ++i) {
  2830. args[i+l] = arguments[i];
  2831. }
  2832. return _apply(f, this, args);
  2833. };
  2834. }
  2835. /**
  2836. * Lift all the functions/methods on src
  2837. * @param {object|function} src source whose functions will be lifted
  2838. * @param {function?} combine optional function for customizing the lifting
  2839. * process. It is passed dst, the lifted function, and the property name of
  2840. * the original function on src.
  2841. * @param {(object|function)?} dst option destination host onto which to place lifted
  2842. * functions. If not provided, liftAll returns a new object.
  2843. * @returns {*} If dst is provided, returns dst with lifted functions as
  2844. * properties. If dst not provided, returns a new object with lifted functions.
  2845. */
  2846. function liftAll(src, combine, dst) {
  2847. return _liftAll(lift, combine, dst, src);
  2848. }
  2849. /**
  2850. * Takes an object that responds to the resolver interface, and returns
  2851. * a function that will resolve or reject it depending on how it is called.
  2852. *
  2853. * @example
  2854. * function callbackTakingFunction(callback) {
  2855. * if(somethingWrongHappened) {
  2856. * callback(error);
  2857. * } else {
  2858. * callback(null, interestingValue);
  2859. * }
  2860. * }
  2861. *
  2862. * var when = require('when'), nodefn = require('when/node/function');
  2863. *
  2864. * var deferred = when.defer();
  2865. * callbackTakingFunction(nodefn.createCallback(deferred.resolver));
  2866. *
  2867. * deferred.promise.then(function(interestingValue) {
  2868. * // Use interestingValue
  2869. * });
  2870. *
  2871. * @param {Resolver} resolver that will be 'attached' to the callback
  2872. * @returns {Function} a node-style callback function
  2873. */
  2874. function createCallback(resolver) {
  2875. return function(err, value) {
  2876. if(err) {
  2877. resolver.reject(err);
  2878. } else if(arguments.length > 2) {
  2879. resolver.resolve(slice.call(arguments, 1));
  2880. } else {
  2881. resolver.resolve(value);
  2882. }
  2883. };
  2884. }
  2885. /**
  2886. * Attaches a node-style callback to a promise, ensuring the callback is
  2887. * called for either fulfillment or rejection. Returns a promise with the same
  2888. * state as the passed-in promise.
  2889. *
  2890. * @example
  2891. * var deferred = when.defer();
  2892. *
  2893. * function callback(err, value) {
  2894. * // Handle err or use value
  2895. * }
  2896. *
  2897. * bindCallback(deferred.promise, callback);
  2898. *
  2899. * deferred.resolve('interesting value');
  2900. *
  2901. * @param {Promise} promise The promise to be attached to.
  2902. * @param {Function} callback The node-style callback to attach.
  2903. * @returns {Promise} A promise with the same state as the passed-in promise.
  2904. */
  2905. function bindCallback(promise, callback) {
  2906. promise = when(promise);
  2907. if (callback) {
  2908. promise.then(success, wrapped);
  2909. }
  2910. return promise;
  2911. function success(value) {
  2912. wrapped(null, value);
  2913. }
  2914. function wrapped(err, value) {
  2915. setTimer(function () {
  2916. callback(err, value);
  2917. }, 0);
  2918. }
  2919. }
  2920. /**
  2921. * Takes a node-style callback and returns new function that accepts a
  2922. * promise, calling the original callback when the promise is either
  2923. * fulfilled or rejected with the appropriate arguments.
  2924. *
  2925. * @example
  2926. * var deferred = when.defer();
  2927. *
  2928. * function callback(err, value) {
  2929. * // Handle err or use value
  2930. * }
  2931. *
  2932. * var wrapped = liftCallback(callback);
  2933. *
  2934. * // `wrapped` can now be passed around at will
  2935. * wrapped(deferred.promise);
  2936. *
  2937. * deferred.resolve('interesting value');
  2938. *
  2939. * @param {Function} callback The node-style callback to wrap.
  2940. * @returns {Function} The lifted, promise-accepting function.
  2941. */
  2942. function liftCallback(callback) {
  2943. return function(promise) {
  2944. return bindCallback(promise, callback);
  2945. };
  2946. }
  2947. });
  2948. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2949. },{"./lib/apply":12,"./lib/env":22,"./lib/liftAll":24,"./when":38}],33:[function(require,module,exports){
  2950. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2951. /**
  2952. * parallel.js
  2953. *
  2954. * Run a set of task functions in parallel. All tasks will
  2955. * receive the same args
  2956. *
  2957. * @author Brian Cavalier
  2958. * @author John Hann
  2959. */
  2960. (function(define) {
  2961. define(function(require) {
  2962. var when = require('./when');
  2963. var all = when.Promise.all;
  2964. var slice = Array.prototype.slice;
  2965. /**
  2966. * Run array of tasks in parallel
  2967. * @param tasks {Array|Promise} array or promiseForArray of task functions
  2968. * @param [args] {*} arguments to be passed to all tasks
  2969. * @return {Promise} promise for array containing the
  2970. * result of each task in the array position corresponding
  2971. * to position of the task in the tasks array
  2972. */
  2973. return function parallel(tasks /*, args... */) {
  2974. return all(slice.call(arguments, 1)).then(function(args) {
  2975. return when.map(tasks, function(task) {
  2976. return task.apply(void 0, args);
  2977. });
  2978. });
  2979. };
  2980. });
  2981. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  2982. },{"./when":38}],34:[function(require,module,exports){
  2983. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2984. /**
  2985. * pipeline.js
  2986. *
  2987. * Run a set of task functions in sequence, passing the result
  2988. * of the previous as an argument to the next. Like a shell
  2989. * pipeline, e.g. `cat file.txt | grep 'foo' | sed -e 's/foo/bar/g'
  2990. *
  2991. * @author Brian Cavalier
  2992. * @author John Hann
  2993. */
  2994. (function(define) {
  2995. define(function(require) {
  2996. var when = require('./when');
  2997. var all = when.Promise.all;
  2998. var slice = Array.prototype.slice;
  2999. /**
  3000. * Run array of tasks in a pipeline where the next
  3001. * tasks receives the result of the previous. The first task
  3002. * will receive the initialArgs as its argument list.
  3003. * @param tasks {Array|Promise} array or promise for array of task functions
  3004. * @param [initialArgs...] {*} arguments to be passed to the first task
  3005. * @return {Promise} promise for return value of the final task
  3006. */
  3007. return function pipeline(tasks /* initialArgs... */) {
  3008. // Self-optimizing function to run first task with multiple
  3009. // args using apply, but subsequence tasks via direct invocation
  3010. var runTask = function(args, task) {
  3011. runTask = function(arg, task) {
  3012. return task(arg);
  3013. };
  3014. return task.apply(null, args);
  3015. };
  3016. return all(slice.call(arguments, 1)).then(function(args) {
  3017. return when.reduce(tasks, function(arg, task) {
  3018. return runTask(arg, task);
  3019. }, args);
  3020. });
  3021. };
  3022. });
  3023. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  3024. },{"./when":38}],35:[function(require,module,exports){
  3025. /** @license MIT License (c) copyright 2012-2013 original author or authors */
  3026. /**
  3027. * poll.js
  3028. *
  3029. * Helper that polls until cancelled or for a condition to become true.
  3030. *
  3031. * @author Scott Andrews
  3032. */
  3033. (function (define) { 'use strict';
  3034. define(function(require) {
  3035. var when = require('./when');
  3036. var attempt = when['try'];
  3037. var cancelable = require('./cancelable');
  3038. /**
  3039. * Periodically execute the task function on the msec delay. The result of
  3040. * the task may be verified by watching for a condition to become true. The
  3041. * returned deferred is cancellable if the polling needs to be cancelled
  3042. * externally before reaching a resolved state.
  3043. *
  3044. * The next vote is scheduled after the results of the current vote are
  3045. * verified and rejected.
  3046. *
  3047. * Polling may be terminated by the verifier returning a truthy value,
  3048. * invoking cancel() on the returned promise, or the task function returning
  3049. * a rejected promise.
  3050. *
  3051. * Usage:
  3052. *
  3053. * var count = 0;
  3054. * function doSomething() { return count++ }
  3055. *
  3056. * // poll until cancelled
  3057. * var p = poll(doSomething, 1000);
  3058. * ...
  3059. * p.cancel();
  3060. *
  3061. * // poll until condition is met
  3062. * poll(doSomething, 1000, function(result) { return result > 10 })
  3063. * .then(function(result) { assert result == 10 });
  3064. *
  3065. * // delay first vote
  3066. * poll(doSomething, 1000, anyFunc, true);
  3067. *
  3068. * @param task {Function} function that is executed after every timeout
  3069. * @param interval {number|Function} timeout in milliseconds
  3070. * @param [verifier] {Function} function to evaluate the result of the vote.
  3071. * May return a {Promise} or a {Boolean}. Rejecting the promise or a
  3072. * falsey value will schedule the next vote.
  3073. * @param [delayInitialTask] {boolean} if truthy, the first vote is scheduled
  3074. * instead of immediate
  3075. *
  3076. * @returns {Promise}
  3077. */
  3078. return function poll(task, interval, verifier, delayInitialTask) {
  3079. var deferred, canceled, reject;
  3080. canceled = false;
  3081. deferred = cancelable(when.defer(), function () { canceled = true; });
  3082. reject = deferred.reject;
  3083. verifier = verifier || function () { return false; };
  3084. if (typeof interval !== 'function') {
  3085. interval = (function (interval) {
  3086. return function () { return when().delay(interval); };
  3087. })(interval);
  3088. }
  3089. function certify(result) {
  3090. deferred.resolve(result);
  3091. }
  3092. function schedule(result) {
  3093. attempt(interval).then(vote, reject);
  3094. if (result !== void 0) {
  3095. deferred.notify(result);
  3096. }
  3097. }
  3098. function vote() {
  3099. if (canceled) { return; }
  3100. when(task(),
  3101. function (result) {
  3102. when(verifier(result),
  3103. function (verification) {
  3104. return verification ? certify(result) : schedule(result);
  3105. },
  3106. function () { schedule(result); }
  3107. );
  3108. },
  3109. reject
  3110. );
  3111. }
  3112. if (delayInitialTask) {
  3113. schedule();
  3114. } else {
  3115. // if task() is blocking, vote will also block
  3116. vote();
  3117. }
  3118. // make the promise cancelable
  3119. deferred.promise = Object.create(deferred.promise);
  3120. deferred.promise.cancel = deferred.cancel;
  3121. return deferred.promise;
  3122. };
  3123. });
  3124. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  3125. },{"./cancelable":4,"./when":38}],36:[function(require,module,exports){
  3126. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  3127. /**
  3128. * sequence.js
  3129. *
  3130. * Run a set of task functions in sequence. All tasks will
  3131. * receive the same args.
  3132. *
  3133. * @author Brian Cavalier
  3134. * @author John Hann
  3135. */
  3136. (function(define) {
  3137. define(function(require) {
  3138. var when = require('./when');
  3139. var all = when.Promise.all;
  3140. var slice = Array.prototype.slice;
  3141. /**
  3142. * Run array of tasks in sequence with no overlap
  3143. * @param tasks {Array|Promise} array or promiseForArray of task functions
  3144. * @param [args] {*} arguments to be passed to all tasks
  3145. * @return {Promise} promise for an array containing
  3146. * the result of each task in the array position corresponding
  3147. * to position of the task in the tasks array
  3148. */
  3149. return function sequence(tasks /*, args... */) {
  3150. var results = [];
  3151. return all(slice.call(arguments, 1)).then(function(args) {
  3152. return when.reduce(tasks, function(results, task) {
  3153. return when(task.apply(void 0, args), addResult);
  3154. }, results);
  3155. });
  3156. function addResult(result) {
  3157. results.push(result);
  3158. return results;
  3159. }
  3160. };
  3161. });
  3162. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  3163. },{"./when":38}],37:[function(require,module,exports){
  3164. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  3165. /**
  3166. * timeout.js
  3167. *
  3168. * Helper that returns a promise that rejects after a specified timeout,
  3169. * if not explicitly resolved or rejected before that.
  3170. *
  3171. * @author Brian Cavalier
  3172. * @author John Hann
  3173. */
  3174. (function(define) {
  3175. define(function(require) {
  3176. var when = require('./when');
  3177. /**
  3178. * @deprecated Use when(trigger).timeout(ms)
  3179. */
  3180. return function timeout(msec, trigger) {
  3181. return when(trigger).timeout(msec);
  3182. };
  3183. });
  3184. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  3185. },{"./when":38}],38:[function(require,module,exports){
  3186. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  3187. /**
  3188. * Promises/A+ and when() implementation
  3189. * when is part of the cujoJS family of libraries (http://cujojs.com/)
  3190. * @author Brian Cavalier
  3191. * @author John Hann
  3192. */
  3193. (function(define) { 'use strict';
  3194. define(function (require) {
  3195. var timed = require('./lib/decorators/timed');
  3196. var array = require('./lib/decorators/array');
  3197. var flow = require('./lib/decorators/flow');
  3198. var fold = require('./lib/decorators/fold');
  3199. var inspect = require('./lib/decorators/inspect');
  3200. var generate = require('./lib/decorators/iterate');
  3201. var progress = require('./lib/decorators/progress');
  3202. var withThis = require('./lib/decorators/with');
  3203. var unhandledRejection = require('./lib/decorators/unhandledRejection');
  3204. var TimeoutError = require('./lib/TimeoutError');
  3205. var Promise = [array, flow, fold, generate, progress,
  3206. inspect, withThis, timed, unhandledRejection]
  3207. .reduce(function(Promise, feature) {
  3208. return feature(Promise);
  3209. }, require('./lib/Promise'));
  3210. var apply = require('./lib/apply')(Promise);
  3211. // Public API
  3212. when.promise = promise; // Create a pending promise
  3213. when.resolve = Promise.resolve; // Create a resolved promise
  3214. when.reject = Promise.reject; // Create a rejected promise
  3215. when.lift = lift; // lift a function to return promises
  3216. when['try'] = attempt; // call a function and return a promise
  3217. when.attempt = attempt; // alias for when.try
  3218. when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
  3219. when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
  3220. when.join = join; // Join 2 or more promises
  3221. when.all = all; // Resolve a list of promises
  3222. when.settle = settle; // Settle a list of promises
  3223. when.any = lift(Promise.any); // One-winner race
  3224. when.some = lift(Promise.some); // Multi-winner race
  3225. when.race = lift(Promise.race); // First-to-settle race
  3226. when.map = map; // Array.map() for promises
  3227. when.filter = filter; // Array.filter() for promises
  3228. when.reduce = lift(Promise.reduce); // Array.reduce() for promises
  3229. when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
  3230. when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
  3231. when.Promise = Promise; // Promise constructor
  3232. when.defer = defer; // Create a {promise, resolve, reject} tuple
  3233. // Error types
  3234. when.TimeoutError = TimeoutError;
  3235. /**
  3236. * Get a trusted promise for x, or by transforming x with onFulfilled
  3237. *
  3238. * @param {*} x
  3239. * @param {function?} onFulfilled callback to be called when x is
  3240. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  3241. * will be invoked immediately.
  3242. * @param {function?} onRejected callback to be called when x is
  3243. * rejected.
  3244. * @param {function?} onProgress callback to be called when progress updates
  3245. * are issued for x. @deprecated
  3246. * @returns {Promise} a new promise that will fulfill with the return
  3247. * value of callback or errback or the completion value of promiseOrValue if
  3248. * callback and/or errback is not supplied.
  3249. */
  3250. function when(x, onFulfilled, onRejected, onProgress) {
  3251. var p = Promise.resolve(x);
  3252. if (arguments.length < 2) {
  3253. return p;
  3254. }
  3255. return p.then(onFulfilled, onRejected, onProgress);
  3256. }
  3257. /**
  3258. * Creates a new promise whose fate is determined by resolver.
  3259. * @param {function} resolver function(resolve, reject, notify)
  3260. * @returns {Promise} promise whose fate is determine by resolver
  3261. */
  3262. function promise(resolver) {
  3263. return new Promise(resolver);
  3264. }
  3265. /**
  3266. * Lift the supplied function, creating a version of f that returns
  3267. * promises, and accepts promises as arguments.
  3268. * @param {function} f
  3269. * @returns {Function} version of f that returns promises
  3270. */
  3271. function lift(f) {
  3272. return function() {
  3273. for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
  3274. a[i] = arguments[i];
  3275. }
  3276. return apply(f, this, a);
  3277. };
  3278. }
  3279. /**
  3280. * Call f in a future turn, with the supplied args, and return a promise
  3281. * for the result.
  3282. * @param {function} f
  3283. * @returns {Promise}
  3284. */
  3285. function attempt(f /*, args... */) {
  3286. /*jshint validthis:true */
  3287. for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
  3288. a[i] = arguments[i+1];
  3289. }
  3290. return apply(f, this, a);
  3291. }
  3292. /**
  3293. * Creates a {promise, resolver} pair, either or both of which
  3294. * may be given out safely to consumers.
  3295. * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
  3296. */
  3297. function defer() {
  3298. return new Deferred();
  3299. }
  3300. function Deferred() {
  3301. var p = Promise._defer();
  3302. function resolve(x) { p._handler.resolve(x); }
  3303. function reject(x) { p._handler.reject(x); }
  3304. function notify(x) { p._handler.notify(x); }
  3305. this.promise = p;
  3306. this.resolve = resolve;
  3307. this.reject = reject;
  3308. this.notify = notify;
  3309. this.resolver = { resolve: resolve, reject: reject, notify: notify };
  3310. }
  3311. /**
  3312. * Determines if x is promise-like, i.e. a thenable object
  3313. * NOTE: Will return true for *any thenable object*, and isn't truly
  3314. * safe, since it may attempt to access the `then` property of x (i.e.
  3315. * clever/malicious getters may do weird things)
  3316. * @param {*} x anything
  3317. * @returns {boolean} true if x is promise-like
  3318. */
  3319. function isPromiseLike(x) {
  3320. return x && typeof x.then === 'function';
  3321. }
  3322. /**
  3323. * Return a promise that will resolve only once all the supplied arguments
  3324. * have resolved. The resolution value of the returned promise will be an array
  3325. * containing the resolution values of each of the arguments.
  3326. * @param {...*} arguments may be a mix of promises and values
  3327. * @returns {Promise}
  3328. */
  3329. function join(/* ...promises */) {
  3330. return Promise.all(arguments);
  3331. }
  3332. /**
  3333. * Return a promise that will fulfill once all input promises have
  3334. * fulfilled, or reject when any one input promise rejects.
  3335. * @param {array|Promise} promises array (or promise for an array) of promises
  3336. * @returns {Promise}
  3337. */
  3338. function all(promises) {
  3339. return when(promises, Promise.all);
  3340. }
  3341. /**
  3342. * Return a promise that will always fulfill with an array containing
  3343. * the outcome states of all input promises. The returned promise
  3344. * will only reject if `promises` itself is a rejected promise.
  3345. * @param {array|Promise} promises array (or promise for an array) of promises
  3346. * @returns {Promise} promise for array of settled state descriptors
  3347. */
  3348. function settle(promises) {
  3349. return when(promises, Promise.settle);
  3350. }
  3351. /**
  3352. * Promise-aware array map function, similar to `Array.prototype.map()`,
  3353. * but input array may contain promises or values.
  3354. * @param {Array|Promise} promises array of anything, may contain promises and values
  3355. * @param {function(x:*, index:Number):*} mapFunc map function which may
  3356. * return a promise or value
  3357. * @returns {Promise} promise that will fulfill with an array of mapped values
  3358. * or reject if any input promise rejects.
  3359. */
  3360. function map(promises, mapFunc) {
  3361. return when(promises, function(promises) {
  3362. return Promise.map(promises, mapFunc);
  3363. });
  3364. }
  3365. /**
  3366. * Filter the provided array of promises using the provided predicate. Input may
  3367. * contain promises and values
  3368. * @param {Array|Promise} promises array of promises and values
  3369. * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
  3370. * Must return truthy (or promise for truthy) for items to retain.
  3371. * @returns {Promise} promise that will fulfill with an array containing all items
  3372. * for which predicate returned truthy.
  3373. */
  3374. function filter(promises, predicate) {
  3375. return when(promises, function(promises) {
  3376. return Promise.filter(promises, predicate);
  3377. });
  3378. }
  3379. return when;
  3380. });
  3381. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  3382. },{"./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])
  3383. //# sourceMappingURL=when.debug.js.map
  3384. (1)
  3385. });
  3386. ;