when.js 99 KB

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