Changeset 489 for Dev/trunk/src/node_modules/q
- Timestamp:
- 03/08/14 11:41:10 (11 years ago)
- Location:
- Dev/trunk/src/node_modules/q
- Files:
-
- 3 added
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
Dev/trunk/src/node_modules/q/README.md
r484 r489 35 35 36 36 ```javascript 37 Q.fcall( step1)38 .then( step2)39 .then( step3)40 .then( step4)37 Q.fcall(promisedStep1) 38 .then(promisedStep2) 39 .then(promisedStep3) 40 .then(promisedStep4) 41 41 .then(function (value4) { 42 42 // Do something with value4 43 }, function (error) { 44 // Handle any error from step1 through step4 43 }) 44 .catch(function (error) { 45 // Handle any error from all above steps 45 46 }) 46 47 .done(); 47 48 ``` 48 49 49 With this approach, you also get implicit error propagation, 50 just like ``try``, ``catch``, and ``finally``. An error in 51 ``step1`` will flow all the way to ``step5``, where itâs52 caught and handled. 50 With this approach, you also get implicit error propagation, just like `try`, 51 `catch`, and `finally`. An error in `promisedStep1` will flow all the way to 52 the `catch` function, where itâs caught and handled. (Here `promisedStepN` is 53 a version of `stepN` that returns a promise.) 53 54 54 55 The callback approach is called an âinversion of controlâ. … … 77 78 78 79 Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more. 79 Additionally, there are many libraries that produce and consume Q promises for 80 everything from file system/database access or RPC to templating. For a list of 81 some of the more popular ones, see [Libraries][]. 82 83 Please join the Q-Continuum [mailing list](https://groups.google.com/forum/#!forum/q-continuum). 84 80 81 ## Resources 82 83 Our [wiki][] contains a number of useful resources, including: 84 85 - A method-by-method [Q API reference][reference]. 86 - A growing [examples gallery][examples], showing how Q can be used to make 87 everything better. From XHR to database access to accessing the Flickr API, 88 Q is there for you. 89 - There are many libraries that produce and consume Q promises for everything 90 from file system/database access or RPC to templating. For a list of some of 91 the more popular ones, see [Libraries][]. 92 - If you want materials that introduce the promise concept generally, and the 93 below tutorial isn't doing it for you, check out our collection of 94 [presentations, blog posts, and podcasts][resources]. 95 - A guide for those [coming from jQuery's `$.Deferred`][jquery]. 96 97 We'd also love to have you join the Q-Continuum [mailing list][]. 98 99 [wiki]: https://github.com/kriskowal/q/wiki 100 [reference]: https://github.com/kriskowal/q/wiki/API-Reference 101 [examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery 85 102 [Libraries]: https://github.com/kriskowal/q/wiki/Libraries 103 [resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources 104 [jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery 105 [mailing list]: https://groups.google.com/forum/#!forum/q-continuum 86 106 87 107 … … 109 129 guarantee when mentally tracing the flow of your code, namely that 110 130 ``then`` will always return before either handler is executed. 131 132 In this tutorial, we begin with how to consume and work with promises. We'll 133 talk about how to create them, and thus create functions like 134 `promiseMeSomething` that return promises, [below](#the-beginning). 111 135 112 136 … … 321 345 var funcs = [foo, bar, baz, qux]; 322 346 323 var result = Q .resolve(initialVal);347 var result = Q(initialVal); 324 348 funcs.forEach(function (f) { 325 349 result = result.then(f); … … 333 357 return funcs.reduce(function (soFar, f) { 334 358 return soFar.then(f); 335 }, Q .resolve(initialVal));359 }, Q(initialVal)); 336 360 ``` 337 361 … … 518 542 var deferred = Q.defer(); 519 543 Q.when(promise, deferred.resolve); 520 Q.when(delay(ms),function () {544 delay(ms).then(function () { 521 545 deferred.reject(new Error("Timed out")); 522 546 }); … … 617 641 618 642 ```javascript 619 return Q .when($.ajax(...))643 return Q($.ajax(...)) 620 644 .then(function () { 621 645 }); … … 685 709 686 710 If you're working with functions that make use of the Node.js callback pattern, 687 Q provides a few useful utility functions for converting between them. The 688 most straightforward are probably `Q.nfcall` and `Q.nfapply` ("Node function 689 call/apply") for calling Node.js-style functions and getting back a promise: 711 where callbacks are in the form of `function(err, result)`, Q provides a few 712 useful utility functions for converting between them. The most straightforward 713 are probably `Q.nfcall` and `Q.nfapply` ("Node function call/apply") for calling 714 Node.js-style functions and getting back a promise: 690 715 691 716 ```javascript … … 776 801 to many users, you should probably keep it off. But in development, go for it! 777 802 778 ## Reference779 780 A method-by-method [Q API reference][reference] is available on the wiki.781 782 [reference]: https://github.com/kriskowal/q/wiki/API-Reference783 784 ## More Examples785 786 A growing [examples gallery][examples] is available on the wiki, showing how Q787 can be used to make everything better. From XHR to database access to accessing788 the Flickr API, Q is there for you.789 790 [examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery791 792 803 ## Tests 793 804 … … 796 807 [tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html 797 808 798 --- 799 800 Copyright 2009 -2012Kristopher Michael Kowal809 ## License 810 811 Copyright 2009â2013 Kristopher Michael Kowal 801 812 MIT License (enclosed) 802 813 -
Dev/trunk/src/node_modules/q/package.json
r484 r489 1 1 { 2 2 "name": "q", 3 "version": "0.9. 6",3 "version": "0.9.7", 4 4 "description": "A library for promises (CommonJS/Promises/A,B,D)", 5 5 "homepage": "https://github.com/kriskowal/q", … … 43 43 "url": "http://github.com/kriskowal/q/issues" 44 44 }, 45 "licenses": [ 46 { 47 "type": "MIT", 48 "url": "http://github.com/kriskowal/q/raw/master/LICENSE" 49 } 50 ], 45 "license": { 46 "type": "MIT", 47 "url": "http://github.com/kriskowal/q/raw/master/LICENSE" 48 }, 51 49 "main": "q.js", 52 50 "repository": { … … 60 58 "dependencies": {}, 61 59 "devDependencies": { 62 "jshint": "~2.1. 3",60 "jshint": "~2.1.9", 63 61 "cover": "*", 64 "jasmine-node": "1. 2.2",62 "jasmine-node": "1.11.0", 65 63 "opener": "*", 66 64 "promises-aplus-tests": "1.x", 67 65 "grunt": "~0.4.1", 68 66 "grunt-cli": "~0.1.9", 69 "grunt-contrib-uglify": "~0.2.2" 67 "grunt-contrib-uglify": "~0.2.2", 68 "matcha": "~0.2.0" 70 69 }, 71 70 "scripts": { 72 71 "test": "jasmine-node spec && promises-aplus-tests spec/aplus-adapter", 73 72 "test-browser": "opener spec/q-spec.html", 73 "benchmark": "matcha", 74 74 "lint": "jshint q.js", 75 75 "cover": "cover run node_modules/jasmine-node/bin/jasmine-node spec && cover report html && opener cover_html/index.html", … … 87 87 "test": "./spec" 88 88 }, 89 "readme": "[](http://travis-ci.org/kriskowal/q)\n\n<a href=\"http://promises-aplus.github.com/promises-spec\">\n <img src=\"http://promises-aplus.github.com/promises-spec/assets/logo-small.png\"\n align=\"right\" alt=\"Promises/A+ logo\" />\n</a>\n\nIf a function cannot return a value or throw an exception without\nblocking, it can return a promise instead. A promise is an object\nthat represents the return value or the thrown exception that the\nfunction may eventually provide. A promise can also be used as a\nproxy for a [remote object][Q-Connection] to overcome latency.\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nOn the first pass, promises can mitigate the â[Pyramid of\nDoom][POD]â: the situation where code marches to the right faster\nthan it marches forward.\n\n[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/\n\n```javascript\nstep1(function (value1) {\n step2(value1, function(value2) {\n step3(value2, function(value3) {\n step4(value3, function(value4) {\n // Do something with value4\n });\n });\n });\n});\n```\n\nWith a promise library, you can flatten the pyramid.\n\n```javascript\nQ.fcall( step1)\n.then(step2)\n.then(step3)\n.then(step4)\n.then(function (value4) {\n // Do something with value4\n}, function (error) {\n // Handle any error from step1 through step4\n})\n.done();\n```\n\nWith this approach, you also get implicit error propagation,\njust like ``try``, ``catch``, and ``finally``. An error in\n``step1`` will flow all the way to ``step5``, where itâs\ncaught and handled.\n\nThe callback approach is called an âinversion of controlâ.\nA function that accepts a callback instead of a return value\nis saying, âDonât call me, Iâll call you.â. Promises\n[un-invert][IOC] the inversion, cleanly separating the input\narguments from control flow arguments. This simplifies the\nuse and creation of APIâs, particularly variadic,\nrest and spread arguments.\n\n[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript\n\n\n## Getting Started\n\nThe Q module can be loaded as:\n\n- A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and\n gzipped.\n- A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as\n the [q](https://npmjs.org/package/q) package\n- An AMD module\n- A [component](https://github.com/component/component) as ``microjs/q``\n- Using [bower](http://bower.io/) as ``q``\n- Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)\n\nQ can exchange promises with jQuery, Dojo, When.js, WinJS, and more.\nAdditionally, there are many libraries that produce and consume Q promises for\neverything from file system/database access or RPC to templating. For a list of\nsome of the more popular ones, see [Libraries][].\n\nPlease join the Q-Continuum [mailing list](https://groups.google.com/forum/#!forum/q-continuum).\n\n[Libraries]: https://github.com/kriskowal/q/wiki/Libraries\n\n\n## Tutorial\n\nPromises have a ``then`` method, which you can use to get the eventual\nreturn value (fulfillment) or thrown exception (rejection).\n\n```javascript\npromiseMeSomething()\n.then(function (value) {\n}, function (reason) {\n});\n```\n\nIf ``promiseMeSomething`` returns a promise that gets fulfilled later\nwith a return value, the first function (the fulfillment handler) will be\ncalled with the value. However, if the ``promiseMeSomething`` function\ngets rejected later by a thrown exception, the second function (the\nrejection handler) will be called with the exception.\n\nNote that resolution of a promise is always asynchronous: that is, the\nfulfillment or rejection handler will always be called in the next turn of the\nevent loop (i.e. `process.nextTick` in Node). This gives you a nice\nguarantee when mentally tracing the flow of your code, namely that\n``then`` will always return before either handler is executed.\n\n\n### Propagation\n\nThe ``then`` method returns a promise, which in this example, Iâm\nassigning to ``outputPromise``.\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (input) {\n}, function (reason) {\n});\n```\n\nThe ``outputPromise`` variable becomes a new promise for the return\nvalue of either handler. Since a function can only either return a\nvalue or throw an exception, only one handler will ever be called and it\nwill be responsible for resolving ``outputPromise``.\n\n- If you return a value in a handler, ``outputPromise`` will get\n fulfilled.\n\n- If you throw an exception in a handler, ``outputPromise`` will get\n rejected.\n\n- If you return a **promise** in a handler, ``outputPromise`` will\n âbecomeâ that promise. Being able to become a new promise is useful\n for managing delays, combining results, or recovering from errors.\n\nIf the ``getInputPromise()`` promise gets rejected and you omit the\nrejection handler, the **error** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (value) {\n});\n```\n\nIf the input promise gets fulfilled and you omit the fulfillment handler, the\n**value** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(null, function (error) {\n});\n```\n\nQ promises provide a ``fail`` shorthand for ``then`` when you are only\ninterested in handling the error:\n\n```javascript\nvar outputPromise = getInputPromise()\n.fail(function (error) {\n});\n```\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `catch` instead of `fail`.\n\nPromises also have a ``fin`` function that is like a ``finally`` clause.\nThe final handler gets called, with no arguments, when the promise\nreturned by ``getInputPromise()`` either returns a value or throws an\nerror. The value returned or error thrown by ``getInputPromise()``\npasses directly to ``outputPromise`` unless the final handler fails, and\nmay be delayed if the final handler returns a promise.\n\n```javascript\nvar outputPromise = getInputPromise()\n.fin(function () {\n // close files, database connections, stop servers, conclude tests\n});\n```\n\n- If the handler returns a value, the value is ignored\n- If the handler throws an error, the error passes to ``outputPromise``\n- If the handler returns a promise, ``outputPromise`` gets postponed. The\n eventual value or error has the same effect as an immediate return\n value or thrown error: a value would be ignored, an error would be\n forwarded.\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `finally` instead of `fin`.\n\n### Chaining\n\nThere are two ways to chain promises. You can chain promises either\ninside or outside handlers. The next two examples are equivalent.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n return getUser(username)\n .then(function (user) {\n // if we get here without an error,\n // the value returned here\n // or the exception thrown here\n // resolves the promise returned\n // by the first line\n })\n});\n```\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n return getUser(username);\n})\n.then(function (user) {\n // if we get here without an error,\n // the value returned here\n // or the exception thrown here\n // resolves the promise returned\n // by the first line\n});\n```\n\nThe only difference is nesting. Itâs useful to nest handlers if you\nneed to capture multiple input values in your closure.\n\n```javascript\nfunction authenticate() {\n return getUsername()\n .then(function (username) {\n return getUser(username);\n })\n // chained because we will not need the user name in the next event\n .then(function (user) {\n return getPassword()\n // nested because we need both user and password next\n .then(function (password) {\n if (user.passwordHash !== hash(password)) {\n throw new Error(\"Can't authenticate\");\n }\n });\n });\n}\n```\n\n\n### Combination\n\nYou can turn an array of promises into a promise for the whole,\nfulfilled array using ``all``.\n\n```javascript\nreturn Q.all([\n eventualAdd(2, 2),\n eventualAdd(10, 20)\n]);\n```\n\nIf you have a promise for an array, you can use ``spread`` as a\nreplacement for ``then``. The ``spread`` function âspreadsâ the\nvalues over the arguments of the fulfillment handler. The rejection handler\nwill get called at the first sign of failure. That is, whichever of\nthe recived promises fails first gets handled by the rejection handler.\n\n```javascript\nfunction eventualAdd(a, b) {\n return Q.spread([a, b], function (a, b) {\n return a + b;\n })\n}\n```\n\nBut ``spread`` calls ``all`` initially, so you can skip it in chains.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n return [username, getUser(username)];\n})\n.spread(function (username, user) {\n});\n```\n\nThe ``all`` function returns a promise for an array of values. When this\npromise is fulfilled, the array contains the fulfillment values of the original\npromises, in the same order as those promises. If one of the given promises\nis rejected, the returned promise is immediately rejected, not waiting for the\nrest of the batch. If you want to wait for all of the promises to either be\nfulfilled or rejected, you can use ``allSettled``.\n\n```javascript\nQ.allSettled(promises)\n.then(function (results) {\n results.forEach(function (result) {\n if (result.state === \"fulfilled\") {\n var value = result.value;\n } else {\n var reason = result.reason;\n }\n });\n});\n```\n\n\n### Sequences\n\nIf you have a number of promise-producing functions that need\nto be run sequentially, you can of course do so manually:\n\n```javascript\nreturn foo(initialVal).then(bar).then(baz).then(qux);\n```\n\nHowever, if you want to run a dynamically constructed sequence of\nfunctions, you'll want something like this:\n\n```javascript\nvar funcs = [foo, bar, baz, qux];\n\nvar result = Q.resolve(initialVal);\nfuncs.forEach(function (f) {\n result = result.then(f);\n});\nreturn result;\n```\n\nYou can make this slightly more compact using `reduce`:\n\n```javascript\nreturn funcs.reduce(function (soFar, f) {\n return soFar.then(f);\n}, Q.resolve(initialVal));\n```\n\nOr, you could use th ultra-compact version:\n\n```javascript\nreturn funcs.reduce(Q.when, Q());\n```\n\n### Handling Errors\n\nOne sometimes-unintuive aspect of promises is that if you throw an\nexception in the fulfillment handler, it will not be be caught by the error\nhandler.\n\n```javascript\nreturn foo()\n.then(function (value) {\n throw new Error(\"Can't bar.\");\n}, function (error) {\n // We only get here if \"foo\" fails\n});\n```\n\nTo see why this is, consider the parallel between promises and\n``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error\nhandler represents a ``catch`` for ``foo()``, while the fulfillment handler\nrepresents code that happens *after* the ``try``/``catch`` block.\nThat code then needs its own ``try``/``catch`` block.\n\nIn terms of promises, this means chaining your rejection handler:\n\n```javascript\nreturn foo()\n.then(function (value) {\n throw new Error(\"Can't bar.\");\n})\n.fail(function (error) {\n // We get here with either foo's error or bar's error\n});\n```\n\n### Progress Notification\n\nIt's possible for promises to report their progress, e.g. for tasks that take a\nlong time like a file upload. Not all promises will implement progress\nnotifications, but for those that do, you can consume the progress values using\na third parameter to ``then``:\n\n```javascript\nreturn uploadFile()\n.then(function () {\n // Success uploading the file\n}, function (err) {\n // There was an error, and we get the reason for error\n}, function (progress) {\n // We get notified of the upload's progress as it is executed\n});\n```\n\nLike `fail`, Q also provides a shorthand for progress callbacks\ncalled `progress`:\n\n```javascript\nreturn uploadFile().progress(function (progress) {\n // We get notified of the upload's progress\n});\n```\n\n### The End\n\nWhen you get to the end of a chain of promises, you should either\nreturn the last promise or end the chain. Since handlers catch\nerrors, itâs an unfortunate pattern that the exceptions can go\nunobserved.\n\nSo, either return it,\n\n```javascript\nreturn foo()\n.then(function () {\n return \"bar\";\n});\n```\n\nOr, end it.\n\n```javascript\nfoo()\n.then(function () {\n return \"bar\";\n})\n.done();\n```\n\nEnding a promise chain makes sure that, if an error doesnât get\nhandled before the end, it will get rethrown and reported.\n\nThis is a stopgap. We are exploring ways to make unhandled errors\nvisible without any explicit handling.\n\n\n### The Beginning\n\nEverything above assumes you get a promise from somewhere else. This\nis the common case. Every once in a while, you will need to create a\npromise from scratch.\n\n#### Using ``Q.fcall``\n\nYou can create a promise from a value using ``Q.fcall``. This returns a\npromise for 10.\n\n```javascript\nreturn Q.fcall(function () {\n return 10;\n});\n```\n\nYou can also use ``fcall`` to get a promise for an exception.\n\n```javascript\nreturn Q.fcall(function () {\n throw new Error(\"Can't do it\");\n});\n```\n\nAs the name implies, ``fcall`` can call functions, or even promised\nfunctions. This uses the ``eventualAdd`` function above to add two\nnumbers.\n\n```javascript\nreturn Q.fcall(eventualAdd, 2, 2);\n```\n\n\n#### Using Deferreds\n\nIf you have to interface with asynchronous functions that are callback-based\ninstead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and\nfriends). But much of the time, the solution will be to use *deferreds*.\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", function (error, text) {\n if (error) {\n deferred.reject(new Error(error));\n } else {\n deferred.resolve(text);\n }\n});\nreturn deferred.promise;\n```\n\nNote that a deferred can be resolved with a value or a promise. The\n``reject`` function is a shorthand for resolving with a rejected\npromise.\n\n```javascript\n// this:\ndeferred.reject(new Error(\"Can't do it\"));\n\n// is shorthand for:\nvar rejection = Q.fcall(function () {\n throw new Error(\"Can't do it\");\n});\ndeferred.resolve(rejection);\n```\n\nThis is a simplified implementation of ``Q.delay``.\n\n```javascript\nfunction delay(ms) {\n var deferred = Q.defer();\n setTimeout(deferred.resolve, ms);\n return deferred.promise;\n}\n```\n\nThis is a simplified implementation of ``Q.timeout``\n\n```javascript\nfunction timeout(promise, ms) {\n var deferred = Q.defer();\n Q.when(promise, deferred.resolve);\n Q.when(delay(ms), function () {\n deferred.reject(new Error(\"Timed out\"));\n });\n return deferred.promise;\n}\n```\n\nFinally, you can send a progress notification to the promise with\n``deferred.notify``.\n\nFor illustration, this is a wrapper for XML HTTP requests in the browser. Note\nthat a more [thorough][XHR] implementation would be in order in practice.\n\n[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73\n\n```javascript\nfunction requestOkText(url) {\n var request = new XMLHttpRequest();\n var deferred = Q.defer();\n\n request.open(\"GET\", url, true);\n request.onload = onload;\n request.onerror = onerror;\n request.onprogress = onprogress;\n request.send();\n\n function onload() {\n if (request.status === 200) {\n deferred.resolve(request.responseText);\n } else {\n deferred.reject(new Error(\"Status code was \" + request.status));\n }\n }\n\n function onerror() {\n deferred.reject(new Error(\"Can't XHR \" + JSON.stringify(url)));\n }\n\n function onprogress(event) {\n deferred.notify(event.loaded / event.total);\n }\n\n return deferred.promise;\n}\n```\n\nBelow is an example of how to use this ``requestOkText`` function:\n\n```javascript\nrequestOkText(\"http://localhost:3000\")\n.then(function (responseText) {\n // If the HTTP response returns 200 OK, log the response text.\n console.log(responseText);\n}, function (error) {\n // If there's an error or a non-200 status code, log the error.\n console.error(error);\n}, function (progress) {\n // Log the progress as it comes in.\n console.log(\"Request progress: \" + Math.round(progress * 100) + \"%\");\n});\n```\n\n### The Middle\n\nIf you are using a function that may return a promise, but just might\nreturn a value if it doesnât need to defer, you can use the âstaticâ\nmethods of the Q library.\n\nThe ``when`` function is the static equivalent for ``then``.\n\n```javascript\nreturn Q.when(valueOrPromise, function (value) {\n}, function (error) {\n});\n```\n\nAll of the other methods on a promise have static analogs with the\nsame name.\n\nThe following are equivalent:\n\n```javascript\nreturn Q.all([a, b]);\n```\n\n```javascript\nreturn Q.fcall(function () {\n return [a, b];\n})\n.all();\n```\n\nWhen working with promises provided by other libraries, you should\nconvert it to a Q promise. Not all promise libraries make the same\nguarantees as Q and certainly donât provide all of the same methods.\nMost libraries only provide a partially functional ``then`` method.\nThis thankfully is all we need to turn them into vibrant Q promises.\n\n```javascript\nreturn Q.when($.ajax(...))\n.then(function () {\n});\n```\n\nIf there is any chance that the promise you receive is not a Q promise\nas provided by your library, you should wrap it using a Q function.\nYou can even use ``Q.invoke`` as a shorthand.\n\n```javascript\nreturn Q.invoke($, 'ajax', ...)\n.then(function () {\n});\n```\n\n\n### Over the Wire\n\nA promise can serve as a proxy for another object, even a remote\nobject. There are methods that allow you to optimistically manipulate\nproperties or call functions. All of these interactions return\npromises, so they can be chained.\n\n```\ndirect manipulation using a promise as a proxy\n-------------------------- -------------------------------\nvalue.foo promise.get(\"foo\")\nvalue.foo = value promise.put(\"foo\", value)\ndelete value.foo promise.del(\"foo\")\nvalue.foo(...args) promise.post(\"foo\", [args])\nvalue.foo(...args) promise.invoke(\"foo\", ...args)\nvalue(...args) promise.fapply([args])\nvalue(...args) promise.fcall(...args)\n```\n\nIf the promise is a proxy for a remote object, you can shave\nround-trips by using these functions instead of ``then``. To take\nadvantage of promises for remote objects, check out [Q-Connection][].\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nEven in the case of non-remote objects, these methods can be used as\nshorthand for particularly-simple fulfillment handlers. For example, you\ncan replace\n\n```javascript\nreturn Q.fcall(function () {\n return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.then(function (value) {\n return value[0].foo;\n});\n```\n\nwith\n\n```javascript\nreturn Q.fcall(function () {\n return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.get(0)\n.get(\"foo\");\n```\n\n\n### Adapting Node\n\nIf you're working with functions that make use of the Node.js callback pattern,\nQ provides a few useful utility functions for converting between them. The\nmost straightforward are probably `Q.nfcall` and `Q.nfapply` (\"Node function\ncall/apply\") for calling Node.js-style functions and getting back a promise:\n\n```javascript\nreturn Q.nfcall(FS.readFile, \"foo.txt\", \"utf-8\");\nreturn Q.nfapply(FS.readFile, [\"foo.txt\", \"utf-8\"]);\n```\n\nIf you are working with methods, instead of simple functions, you can easily\nrun in to the usual problems where passing a method to another functionâlike\n`Q.nfcall`â\"un-binds\" the method from its owner. To avoid this, you can either\nuse `Function.prototype.bind` or some nice shortcut methods we provide:\n\n```javascript\nreturn Q.ninvoke(redisClient, \"get\", \"user:1:id\");\nreturn Q.npost(redisClient, \"get\", [\"user:1:id\"]);\n```\n\nYou can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:\n\n```javascript\nvar readFile = Q.denodeify(FS.readFile);\nreturn readFile(\"foo.txt\", \"utf-8\");\n\nvar redisClientGet = Q.nbind(redisClient.get, redisClient);\nreturn redisClientGet(\"user:1:id\");\n```\n\nFinally, if you're working with raw deferred objects, there is a\n`makeNodeResolver` method on deferreds that can be handy:\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", deferred.makeNodeResolver());\nreturn deferred.promise;\n```\n\n### Long Stack Traces\n\nQ comes with optional support for âlong stack traces,â wherein the `stack`\nproperty of `Error` rejection reasons is rewritten to be traced along\nasynchronous jumps instead of stopping at the most recent one. As an example:\n\n```js\nfunction theDepthsOfMyProgram() {\n Q.delay(100).done(function explode() {\n throw new Error(\"boo!\");\n });\n}\n\ntheDepthsOfMyProgram();\n```\n\nusually would give a rather unhelpful stack trace looking something like\n\n```\nError: boo!\n at explode (/path/to/test.js:3:11)\n at _fulfilled (/path/to/test.js:q:54)\n at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)\n at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)\n at pending (/path/to/q.js:397:39)\n at process.startup.processNextTick.process._tickCallback (node.js:244:9)\n```\n\nBut, if you turn this feature on by setting\n\n```js\nQ.longStackSupport = true;\n```\n\nthen the above code gives a nice stack trace to the tune of\n\n```\nError: boo!\n at explode (/path/to/test.js:3:11)\nFrom previous event:\n at theDepthsOfMyProgram (/path/to/test.js:2:16)\n at Object.<anonymous> (/path/to/test.js:7:1)\n```\n\nNote how you can see the the function that triggered the async operation in the\nstack trace! This is very helpful for debugging, as otherwise you end up getting\nonly the first line, plus a bunch of Q internals, with no sign of where the\noperation started.\n\nThis feature does come with somewhat-serious performance and memory overhead,\nhowever. If you're working with lots of promises, or trying to scale a server\nto many users, you should probably keep it off. But in development, go for it!\n\n## Reference\n\nA method-by-method [Q API reference][reference] is available on the wiki.\n\n[reference]: https://github.com/kriskowal/q/wiki/API-Reference\n\n## More Examples\n\nA growing [examples gallery][examples] is available on the wiki, showing how Q\ncan be used to make everything better. From XHR to database access to accessing\nthe Flickr API, Q is there for you.\n\n[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery\n\n## Tests\n\nYou can view the results of the Q test suite [in your browser][tests]!\n\n[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html\n\n---\n\nCopyright 2009-2012Kristopher Michael Kowal\nMIT License (enclosed)\n\n",89 "readme": "[](http://travis-ci.org/kriskowal/q)\n\n<a href=\"http://promises-aplus.github.com/promises-spec\">\n <img src=\"http://promises-aplus.github.com/promises-spec/assets/logo-small.png\"\n align=\"right\" alt=\"Promises/A+ logo\" />\n</a>\n\nIf a function cannot return a value or throw an exception without\nblocking, it can return a promise instead. A promise is an object\nthat represents the return value or the thrown exception that the\nfunction may eventually provide. A promise can also be used as a\nproxy for a [remote object][Q-Connection] to overcome latency.\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nOn the first pass, promises can mitigate the â[Pyramid of\nDoom][POD]â: the situation where code marches to the right faster\nthan it marches forward.\n\n[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/\n\n```javascript\nstep1(function (value1) {\n step2(value1, function(value2) {\n step3(value2, function(value3) {\n step4(value3, function(value4) {\n // Do something with value4\n });\n });\n });\n});\n```\n\nWith a promise library, you can flatten the pyramid.\n\n```javascript\nQ.fcall(promisedStep1)\n.then(promisedStep2)\n.then(promisedStep3)\n.then(promisedStep4)\n.then(function (value4) {\n // Do something with value4\n})\n.catch(function (error) {\n // Handle any error from all above steps\n})\n.done();\n```\n\nWith this approach, you also get implicit error propagation, just like `try`,\n`catch`, and `finally`. An error in `promisedStep1` will flow all the way to\nthe `catch` function, where itâs caught and handled. (Here `promisedStepN` is\na version of `stepN` that returns a promise.)\n\nThe callback approach is called an âinversion of controlâ.\nA function that accepts a callback instead of a return value\nis saying, âDonât call me, Iâll call you.â. Promises\n[un-invert][IOC] the inversion, cleanly separating the input\narguments from control flow arguments. This simplifies the\nuse and creation of APIâs, particularly variadic,\nrest and spread arguments.\n\n[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript\n\n\n## Getting Started\n\nThe Q module can be loaded as:\n\n- A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and\n gzipped.\n- A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as\n the [q](https://npmjs.org/package/q) package\n- An AMD module\n- A [component](https://github.com/component/component) as ``microjs/q``\n- Using [bower](http://bower.io/) as ``q``\n- Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)\n\nQ can exchange promises with jQuery, Dojo, When.js, WinJS, and more.\n\n## Resources\n\nOur [wiki][] contains a number of useful resources, including:\n\n- A method-by-method [Q API reference][reference].\n- A growing [examples gallery][examples], showing how Q can be used to make\n everything better. From XHR to database access to accessing the Flickr API,\n Q is there for you.\n- There are many libraries that produce and consume Q promises for everything\n from file system/database access or RPC to templating. For a list of some of\n the more popular ones, see [Libraries][].\n- If you want materials that introduce the promise concept generally, and the\n below tutorial isn't doing it for you, check out our collection of\n [presentations, blog posts, and podcasts][resources].\n- A guide for those [coming from jQuery's `$.Deferred`][jquery].\n\nWe'd also love to have you join the Q-Continuum [mailing list][].\n\n[wiki]: https://github.com/kriskowal/q/wiki\n[reference]: https://github.com/kriskowal/q/wiki/API-Reference\n[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery\n[Libraries]: https://github.com/kriskowal/q/wiki/Libraries\n[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources\n[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery\n[mailing list]: https://groups.google.com/forum/#!forum/q-continuum\n\n\n## Tutorial\n\nPromises have a ``then`` method, which you can use to get the eventual\nreturn value (fulfillment) or thrown exception (rejection).\n\n```javascript\npromiseMeSomething()\n.then(function (value) {\n}, function (reason) {\n});\n```\n\nIf ``promiseMeSomething`` returns a promise that gets fulfilled later\nwith a return value, the first function (the fulfillment handler) will be\ncalled with the value. However, if the ``promiseMeSomething`` function\ngets rejected later by a thrown exception, the second function (the\nrejection handler) will be called with the exception.\n\nNote that resolution of a promise is always asynchronous: that is, the\nfulfillment or rejection handler will always be called in the next turn of the\nevent loop (i.e. `process.nextTick` in Node). This gives you a nice\nguarantee when mentally tracing the flow of your code, namely that\n``then`` will always return before either handler is executed.\n\nIn this tutorial, we begin with how to consume and work with promises. We'll\ntalk about how to create them, and thus create functions like\n`promiseMeSomething` that return promises, [below](#the-beginning).\n\n\n### Propagation\n\nThe ``then`` method returns a promise, which in this example, Iâm\nassigning to ``outputPromise``.\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (input) {\n}, function (reason) {\n});\n```\n\nThe ``outputPromise`` variable becomes a new promise for the return\nvalue of either handler. Since a function can only either return a\nvalue or throw an exception, only one handler will ever be called and it\nwill be responsible for resolving ``outputPromise``.\n\n- If you return a value in a handler, ``outputPromise`` will get\n fulfilled.\n\n- If you throw an exception in a handler, ``outputPromise`` will get\n rejected.\n\n- If you return a **promise** in a handler, ``outputPromise`` will\n âbecomeâ that promise. Being able to become a new promise is useful\n for managing delays, combining results, or recovering from errors.\n\nIf the ``getInputPromise()`` promise gets rejected and you omit the\nrejection handler, the **error** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (value) {\n});\n```\n\nIf the input promise gets fulfilled and you omit the fulfillment handler, the\n**value** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(null, function (error) {\n});\n```\n\nQ promises provide a ``fail`` shorthand for ``then`` when you are only\ninterested in handling the error:\n\n```javascript\nvar outputPromise = getInputPromise()\n.fail(function (error) {\n});\n```\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `catch` instead of `fail`.\n\nPromises also have a ``fin`` function that is like a ``finally`` clause.\nThe final handler gets called, with no arguments, when the promise\nreturned by ``getInputPromise()`` either returns a value or throws an\nerror. The value returned or error thrown by ``getInputPromise()``\npasses directly to ``outputPromise`` unless the final handler fails, and\nmay be delayed if the final handler returns a promise.\n\n```javascript\nvar outputPromise = getInputPromise()\n.fin(function () {\n // close files, database connections, stop servers, conclude tests\n});\n```\n\n- If the handler returns a value, the value is ignored\n- If the handler throws an error, the error passes to ``outputPromise``\n- If the handler returns a promise, ``outputPromise`` gets postponed. The\n eventual value or error has the same effect as an immediate return\n value or thrown error: a value would be ignored, an error would be\n forwarded.\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `finally` instead of `fin`.\n\n### Chaining\n\nThere are two ways to chain promises. You can chain promises either\ninside or outside handlers. The next two examples are equivalent.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n return getUser(username)\n .then(function (user) {\n // if we get here without an error,\n // the value returned here\n // or the exception thrown here\n // resolves the promise returned\n // by the first line\n })\n});\n```\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n return getUser(username);\n})\n.then(function (user) {\n // if we get here without an error,\n // the value returned here\n // or the exception thrown here\n // resolves the promise returned\n // by the first line\n});\n```\n\nThe only difference is nesting. Itâs useful to nest handlers if you\nneed to capture multiple input values in your closure.\n\n```javascript\nfunction authenticate() {\n return getUsername()\n .then(function (username) {\n return getUser(username);\n })\n // chained because we will not need the user name in the next event\n .then(function (user) {\n return getPassword()\n // nested because we need both user and password next\n .then(function (password) {\n if (user.passwordHash !== hash(password)) {\n throw new Error(\"Can't authenticate\");\n }\n });\n });\n}\n```\n\n\n### Combination\n\nYou can turn an array of promises into a promise for the whole,\nfulfilled array using ``all``.\n\n```javascript\nreturn Q.all([\n eventualAdd(2, 2),\n eventualAdd(10, 20)\n]);\n```\n\nIf you have a promise for an array, you can use ``spread`` as a\nreplacement for ``then``. The ``spread`` function âspreadsâ the\nvalues over the arguments of the fulfillment handler. The rejection handler\nwill get called at the first sign of failure. That is, whichever of\nthe recived promises fails first gets handled by the rejection handler.\n\n```javascript\nfunction eventualAdd(a, b) {\n return Q.spread([a, b], function (a, b) {\n return a + b;\n })\n}\n```\n\nBut ``spread`` calls ``all`` initially, so you can skip it in chains.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n return [username, getUser(username)];\n})\n.spread(function (username, user) {\n});\n```\n\nThe ``all`` function returns a promise for an array of values. When this\npromise is fulfilled, the array contains the fulfillment values of the original\npromises, in the same order as those promises. If one of the given promises\nis rejected, the returned promise is immediately rejected, not waiting for the\nrest of the batch. If you want to wait for all of the promises to either be\nfulfilled or rejected, you can use ``allSettled``.\n\n```javascript\nQ.allSettled(promises)\n.then(function (results) {\n results.forEach(function (result) {\n if (result.state === \"fulfilled\") {\n var value = result.value;\n } else {\n var reason = result.reason;\n }\n });\n});\n```\n\n\n### Sequences\n\nIf you have a number of promise-producing functions that need\nto be run sequentially, you can of course do so manually:\n\n```javascript\nreturn foo(initialVal).then(bar).then(baz).then(qux);\n```\n\nHowever, if you want to run a dynamically constructed sequence of\nfunctions, you'll want something like this:\n\n```javascript\nvar funcs = [foo, bar, baz, qux];\n\nvar result = Q(initialVal);\nfuncs.forEach(function (f) {\n result = result.then(f);\n});\nreturn result;\n```\n\nYou can make this slightly more compact using `reduce`:\n\n```javascript\nreturn funcs.reduce(function (soFar, f) {\n return soFar.then(f);\n}, Q(initialVal));\n```\n\nOr, you could use th ultra-compact version:\n\n```javascript\nreturn funcs.reduce(Q.when, Q());\n```\n\n### Handling Errors\n\nOne sometimes-unintuive aspect of promises is that if you throw an\nexception in the fulfillment handler, it will not be be caught by the error\nhandler.\n\n```javascript\nreturn foo()\n.then(function (value) {\n throw new Error(\"Can't bar.\");\n}, function (error) {\n // We only get here if \"foo\" fails\n});\n```\n\nTo see why this is, consider the parallel between promises and\n``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error\nhandler represents a ``catch`` for ``foo()``, while the fulfillment handler\nrepresents code that happens *after* the ``try``/``catch`` block.\nThat code then needs its own ``try``/``catch`` block.\n\nIn terms of promises, this means chaining your rejection handler:\n\n```javascript\nreturn foo()\n.then(function (value) {\n throw new Error(\"Can't bar.\");\n})\n.fail(function (error) {\n // We get here with either foo's error or bar's error\n});\n```\n\n### Progress Notification\n\nIt's possible for promises to report their progress, e.g. for tasks that take a\nlong time like a file upload. Not all promises will implement progress\nnotifications, but for those that do, you can consume the progress values using\na third parameter to ``then``:\n\n```javascript\nreturn uploadFile()\n.then(function () {\n // Success uploading the file\n}, function (err) {\n // There was an error, and we get the reason for error\n}, function (progress) {\n // We get notified of the upload's progress as it is executed\n});\n```\n\nLike `fail`, Q also provides a shorthand for progress callbacks\ncalled `progress`:\n\n```javascript\nreturn uploadFile().progress(function (progress) {\n // We get notified of the upload's progress\n});\n```\n\n### The End\n\nWhen you get to the end of a chain of promises, you should either\nreturn the last promise or end the chain. Since handlers catch\nerrors, itâs an unfortunate pattern that the exceptions can go\nunobserved.\n\nSo, either return it,\n\n```javascript\nreturn foo()\n.then(function () {\n return \"bar\";\n});\n```\n\nOr, end it.\n\n```javascript\nfoo()\n.then(function () {\n return \"bar\";\n})\n.done();\n```\n\nEnding a promise chain makes sure that, if an error doesnât get\nhandled before the end, it will get rethrown and reported.\n\nThis is a stopgap. We are exploring ways to make unhandled errors\nvisible without any explicit handling.\n\n\n### The Beginning\n\nEverything above assumes you get a promise from somewhere else. This\nis the common case. Every once in a while, you will need to create a\npromise from scratch.\n\n#### Using ``Q.fcall``\n\nYou can create a promise from a value using ``Q.fcall``. This returns a\npromise for 10.\n\n```javascript\nreturn Q.fcall(function () {\n return 10;\n});\n```\n\nYou can also use ``fcall`` to get a promise for an exception.\n\n```javascript\nreturn Q.fcall(function () {\n throw new Error(\"Can't do it\");\n});\n```\n\nAs the name implies, ``fcall`` can call functions, or even promised\nfunctions. This uses the ``eventualAdd`` function above to add two\nnumbers.\n\n```javascript\nreturn Q.fcall(eventualAdd, 2, 2);\n```\n\n\n#### Using Deferreds\n\nIf you have to interface with asynchronous functions that are callback-based\ninstead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and\nfriends). But much of the time, the solution will be to use *deferreds*.\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", function (error, text) {\n if (error) {\n deferred.reject(new Error(error));\n } else {\n deferred.resolve(text);\n }\n});\nreturn deferred.promise;\n```\n\nNote that a deferred can be resolved with a value or a promise. The\n``reject`` function is a shorthand for resolving with a rejected\npromise.\n\n```javascript\n// this:\ndeferred.reject(new Error(\"Can't do it\"));\n\n// is shorthand for:\nvar rejection = Q.fcall(function () {\n throw new Error(\"Can't do it\");\n});\ndeferred.resolve(rejection);\n```\n\nThis is a simplified implementation of ``Q.delay``.\n\n```javascript\nfunction delay(ms) {\n var deferred = Q.defer();\n setTimeout(deferred.resolve, ms);\n return deferred.promise;\n}\n```\n\nThis is a simplified implementation of ``Q.timeout``\n\n```javascript\nfunction timeout(promise, ms) {\n var deferred = Q.defer();\n Q.when(promise, deferred.resolve);\n delay(ms).then(function () {\n deferred.reject(new Error(\"Timed out\"));\n });\n return deferred.promise;\n}\n```\n\nFinally, you can send a progress notification to the promise with\n``deferred.notify``.\n\nFor illustration, this is a wrapper for XML HTTP requests in the browser. Note\nthat a more [thorough][XHR] implementation would be in order in practice.\n\n[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73\n\n```javascript\nfunction requestOkText(url) {\n var request = new XMLHttpRequest();\n var deferred = Q.defer();\n\n request.open(\"GET\", url, true);\n request.onload = onload;\n request.onerror = onerror;\n request.onprogress = onprogress;\n request.send();\n\n function onload() {\n if (request.status === 200) {\n deferred.resolve(request.responseText);\n } else {\n deferred.reject(new Error(\"Status code was \" + request.status));\n }\n }\n\n function onerror() {\n deferred.reject(new Error(\"Can't XHR \" + JSON.stringify(url)));\n }\n\n function onprogress(event) {\n deferred.notify(event.loaded / event.total);\n }\n\n return deferred.promise;\n}\n```\n\nBelow is an example of how to use this ``requestOkText`` function:\n\n```javascript\nrequestOkText(\"http://localhost:3000\")\n.then(function (responseText) {\n // If the HTTP response returns 200 OK, log the response text.\n console.log(responseText);\n}, function (error) {\n // If there's an error or a non-200 status code, log the error.\n console.error(error);\n}, function (progress) {\n // Log the progress as it comes in.\n console.log(\"Request progress: \" + Math.round(progress * 100) + \"%\");\n});\n```\n\n### The Middle\n\nIf you are using a function that may return a promise, but just might\nreturn a value if it doesnât need to defer, you can use the âstaticâ\nmethods of the Q library.\n\nThe ``when`` function is the static equivalent for ``then``.\n\n```javascript\nreturn Q.when(valueOrPromise, function (value) {\n}, function (error) {\n});\n```\n\nAll of the other methods on a promise have static analogs with the\nsame name.\n\nThe following are equivalent:\n\n```javascript\nreturn Q.all([a, b]);\n```\n\n```javascript\nreturn Q.fcall(function () {\n return [a, b];\n})\n.all();\n```\n\nWhen working with promises provided by other libraries, you should\nconvert it to a Q promise. Not all promise libraries make the same\nguarantees as Q and certainly donât provide all of the same methods.\nMost libraries only provide a partially functional ``then`` method.\nThis thankfully is all we need to turn them into vibrant Q promises.\n\n```javascript\nreturn Q($.ajax(...))\n.then(function () {\n});\n```\n\nIf there is any chance that the promise you receive is not a Q promise\nas provided by your library, you should wrap it using a Q function.\nYou can even use ``Q.invoke`` as a shorthand.\n\n```javascript\nreturn Q.invoke($, 'ajax', ...)\n.then(function () {\n});\n```\n\n\n### Over the Wire\n\nA promise can serve as a proxy for another object, even a remote\nobject. There are methods that allow you to optimistically manipulate\nproperties or call functions. All of these interactions return\npromises, so they can be chained.\n\n```\ndirect manipulation using a promise as a proxy\n-------------------------- -------------------------------\nvalue.foo promise.get(\"foo\")\nvalue.foo = value promise.put(\"foo\", value)\ndelete value.foo promise.del(\"foo\")\nvalue.foo(...args) promise.post(\"foo\", [args])\nvalue.foo(...args) promise.invoke(\"foo\", ...args)\nvalue(...args) promise.fapply([args])\nvalue(...args) promise.fcall(...args)\n```\n\nIf the promise is a proxy for a remote object, you can shave\nround-trips by using these functions instead of ``then``. To take\nadvantage of promises for remote objects, check out [Q-Connection][].\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nEven in the case of non-remote objects, these methods can be used as\nshorthand for particularly-simple fulfillment handlers. For example, you\ncan replace\n\n```javascript\nreturn Q.fcall(function () {\n return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.then(function (value) {\n return value[0].foo;\n});\n```\n\nwith\n\n```javascript\nreturn Q.fcall(function () {\n return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.get(0)\n.get(\"foo\");\n```\n\n\n### Adapting Node\n\nIf you're working with functions that make use of the Node.js callback pattern,\nwhere callbacks are in the form of `function(err, result)`, Q provides a few\nuseful utility functions for converting between them. The most straightforward\nare probably `Q.nfcall` and `Q.nfapply` (\"Node function call/apply\") for calling\nNode.js-style functions and getting back a promise:\n\n```javascript\nreturn Q.nfcall(FS.readFile, \"foo.txt\", \"utf-8\");\nreturn Q.nfapply(FS.readFile, [\"foo.txt\", \"utf-8\"]);\n```\n\nIf you are working with methods, instead of simple functions, you can easily\nrun in to the usual problems where passing a method to another functionâlike\n`Q.nfcall`â\"un-binds\" the method from its owner. To avoid this, you can either\nuse `Function.prototype.bind` or some nice shortcut methods we provide:\n\n```javascript\nreturn Q.ninvoke(redisClient, \"get\", \"user:1:id\");\nreturn Q.npost(redisClient, \"get\", [\"user:1:id\"]);\n```\n\nYou can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:\n\n```javascript\nvar readFile = Q.denodeify(FS.readFile);\nreturn readFile(\"foo.txt\", \"utf-8\");\n\nvar redisClientGet = Q.nbind(redisClient.get, redisClient);\nreturn redisClientGet(\"user:1:id\");\n```\n\nFinally, if you're working with raw deferred objects, there is a\n`makeNodeResolver` method on deferreds that can be handy:\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", deferred.makeNodeResolver());\nreturn deferred.promise;\n```\n\n### Long Stack Traces\n\nQ comes with optional support for âlong stack traces,â wherein the `stack`\nproperty of `Error` rejection reasons is rewritten to be traced along\nasynchronous jumps instead of stopping at the most recent one. As an example:\n\n```js\nfunction theDepthsOfMyProgram() {\n Q.delay(100).done(function explode() {\n throw new Error(\"boo!\");\n });\n}\n\ntheDepthsOfMyProgram();\n```\n\nusually would give a rather unhelpful stack trace looking something like\n\n```\nError: boo!\n at explode (/path/to/test.js:3:11)\n at _fulfilled (/path/to/test.js:q:54)\n at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)\n at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)\n at pending (/path/to/q.js:397:39)\n at process.startup.processNextTick.process._tickCallback (node.js:244:9)\n```\n\nBut, if you turn this feature on by setting\n\n```js\nQ.longStackSupport = true;\n```\n\nthen the above code gives a nice stack trace to the tune of\n\n```\nError: boo!\n at explode (/path/to/test.js:3:11)\nFrom previous event:\n at theDepthsOfMyProgram (/path/to/test.js:2:16)\n at Object.<anonymous> (/path/to/test.js:7:1)\n```\n\nNote how you can see the the function that triggered the async operation in the\nstack trace! This is very helpful for debugging, as otherwise you end up getting\nonly the first line, plus a bunch of Q internals, with no sign of where the\noperation started.\n\nThis feature does come with somewhat-serious performance and memory overhead,\nhowever. If you're working with lots of promises, or trying to scale a server\nto many users, you should probably keep it off. But in development, go for it!\n\n## Tests\n\nYou can view the results of the Q test suite [in your browser][tests]!\n\n[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html\n\n## License\n\nCopyright 2009â2013 Kristopher Michael Kowal\nMIT License (enclosed)\n\n", 90 90 "readmeFilename": "README.md", 91 "_id": "q@0.9. 6",91 "_id": "q@0.9.7", 92 92 "dist": { 93 "shasum": " ff68447a49ea86f1e926dea6eb7487a110c764d5"93 "shasum": "bebb084f592180190176960dd29862d3818f2e06" 94 94 }, 95 "_from": "q@ ",96 "_resolved": "https://registry.npmjs.org/q/-/q-0.9. 6.tgz"95 "_from": "q@0.9.7", 96 "_resolved": "https://registry.npmjs.org/q/-/q-0.9.7.tgz" 97 97 } -
Dev/trunk/src/node_modules/q/q.js
r484 r489 92 92 93 93 function flush() { 94 /* jshint loopfunc: true */ 95 94 96 while (head.next) { 95 97 head = head.next; … … 114 116 // listening "uncaughtException" events (as domains does). 115 117 // Continue in next event to avoid tick recursion. 116 domain && domain.exit(); 118 if (domain) { 119 domain.exit(); 120 } 117 121 setTimeout(flush, 0); 118 domain && domain.enter(); 122 if (domain) { 123 domain.enter(); 124 } 119 125 120 126 throw e; … … 173 179 // http://www.nonblocking.io/2011/06/windownexttick.html 174 180 var channel = new MessageChannel(); 175 channel.port1.onmessage = flush; 181 // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create 182 // working message ports the first time a page loads. 183 channel.port1.onmessage = function () { 184 requestTick = requestPortTick; 185 channel.port1.onmessage = flush; 186 flush(); 187 }; 188 var requestPortTick = function () { 189 // Opera requires us to provide a message payload, regardless of 190 // whether we use it. 191 channel.port2.postMessage(0); 192 }; 176 193 requestTick = function () { 177 channel.port2.postMessage(0); 194 setTimeout(flush, 0); 195 requestPortTick(); 178 196 }; 179 197 … … 199 217 // See Mark Millerâs explanation of what this does. 200 218 // http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming 219 var call = Function.call; 201 220 function uncurryThis(f) { 202 var call = Function.call;203 221 return function () { 204 222 return call.apply(f, arguments); … … 442 460 443 461 /** 444 * C reates fulfilled promises from non-thenables,445 * Passes Q promises through,446 * Coerces other thenables to Q promises.462 * Constructs a promise for an immediate reference, passes promises through, or 463 * coerces promises from different systems. 464 * @param value immediate reference or promise 447 465 */ 448 466 function Q(value) { 449 return resolve(value); 450 } 467 // If the object is already a Promise, return it directly. This enables 468 // the resolve function to both be used to created references from objects, 469 // but to tolerably coerce non-promises to promises. 470 if (isPromise(value)) { 471 return value; 472 } 473 474 // assimilate thenables 475 if (isPromiseAlike(value)) { 476 return coerce(value); 477 } else { 478 return fulfill(value); 479 } 480 } 481 Q.resolve = Q; 451 482 452 483 /** … … 555 586 } 556 587 557 become( resolve(value));588 become(Q(value)); 558 589 }; 559 590 … … 616 647 throw new TypeError("resolver must be a function."); 617 648 } 618 619 649 var deferred = defer(); 620 fcall( 621 resolver, 622 deferred.resolve, 623 deferred.reject, 624 deferred.notify 625 ).fail(deferred.reject); 650 try { 651 resolver(deferred.resolve, deferred.reject, deferred.notify); 652 } catch (reason) { 653 deferred.reject(reason); 654 } 626 655 return deferred.promise; 627 656 } 657 658 // XXX experimental. This method is a way to denote that a local value is 659 // serializable and should be immediately dispatched to a remote upon request, 660 // instead of passing a reference. 661 Q.passByCopy = function (object) { 662 //freeze(object); 663 //passByCopies.set(object, true); 664 return object; 665 }; 666 667 Promise.prototype.passByCopy = function () { 668 //freeze(object); 669 //passByCopies.set(object, true); 670 return this; 671 }; 672 673 /** 674 * If two promises eventually fulfill to the same value, promises that value, 675 * but otherwise rejects. 676 * @param x {Any*} 677 * @param y {Any*} 678 * @returns {Any*} a promise for x and y if they are the same, but a rejection 679 * otherwise. 680 * 681 */ 682 Q.join = function (x, y) { 683 return Q(x).join(y); 684 }; 685 686 Promise.prototype.join = function (that) { 687 return Q([this, that]).spread(function (x, y) { 688 if (x === y) { 689 // TODO: "===" should be Object.is or equiv 690 return x; 691 } else { 692 throw new Error("Can't join: not the same: " + x + " " + y); 693 } 694 }); 695 }; 696 697 /** 698 * Returns a promise for the first of an array of promises to become fulfilled. 699 * @param answers {Array[Any*]} promises to race 700 * @returns {Any*} the first promise to be fulfilled 701 */ 702 Q.race = race; 703 function race(answerPs) { 704 return promise(function(resolve, reject) { 705 // Switch to this once we can assume at least ES5 706 // answerPs.forEach(function(answerP) { 707 // Q(answerP).then(resolve, reject); 708 // }); 709 // Use this in the meantime 710 for (var i = 0, len = answerPs.length; i < len; i++) { 711 Q(answerPs[i]).then(resolve, reject); 712 } 713 }); 714 } 715 716 Promise.prototype.race = function () { 717 return this.then(Q.race); 718 }; 628 719 629 720 /** … … 692 783 return promise; 693 784 } 785 786 Promise.prototype.toString = function () { 787 return "[object Promise]"; 788 }; 694 789 695 790 Promise.prototype.then = function (fulfilled, rejected, progressed) { … … 764 859 }; 765 860 861 /** 862 * Registers an observer on a promise. 863 * 864 * Guarantees: 865 * 866 * 1. that fulfilled and rejected will be called only once. 867 * 2. that either the fulfilled callback or the rejected callback will be 868 * called, but not both. 869 * 3. that fulfilled and rejected will not be called in this turn. 870 * 871 * @param value promise or immediate reference to observe 872 * @param fulfilled function to be called with the fulfilled value 873 * @param rejected function to be called with the rejection exception 874 * @param progressed function to be called on any progress notifications 875 * @return promise for the return value from the invoked callback 876 */ 877 Q.when = when; 878 function when(value, fulfilled, rejected, progressed) { 879 return Q(value).then(fulfilled, rejected, progressed); 880 } 881 766 882 Promise.prototype.thenResolve = function (value) { 767 return when(this, function () { return value; }); 883 return this.then(function () { return value; }); 884 }; 885 886 Q.thenResolve = function (promise, value) { 887 return Q(promise).thenResolve(value); 768 888 }; 769 889 770 890 Promise.prototype.thenReject = function (reason) { 771 return when(this, function () { throw reason; }); 772 }; 773 774 // Chainable methods 775 array_reduce( 776 [ 777 "isFulfilled", "isRejected", "isPending", 778 "dispatch", 779 "when", "spread", 780 "get", "set", "del", "delete", 781 "post", "send", "mapply", "invoke", "mcall", 782 "keys", 783 "fapply", "fcall", "fbind", 784 "all", "allResolved", 785 "timeout", "delay", 786 "catch", "finally", "fail", "fin", "progress", "done", 787 "nfcall", "nfapply", "nfbind", "denodeify", "nbind", 788 "npost", "nsend", "nmapply", "ninvoke", "nmcall", 789 "nodeify" 790 ], 791 function (undefined, name) { 792 Promise.prototype[name] = function () { 793 return Q[name].apply( 794 Q, 795 [this].concat(array_slice(arguments)) 796 ); 797 }; 798 }, 799 void 0 800 ); 801 802 Promise.prototype.toSource = function () { 803 return this.toString(); 804 }; 805 806 Promise.prototype.toString = function () { 807 return "[object Promise]"; 891 return this.then(function () { throw reason; }); 892 }; 893 894 Q.thenReject = function (promise, reason) { 895 return Q(promise).thenReject(reason); 808 896 }; 809 897 … … 855 943 } 856 944 945 Promise.prototype.isPending = function () { 946 return this.inspect().state === "pending"; 947 }; 948 857 949 /** 858 950 * @returns whether the given object is a value or fulfilled … … 864 956 } 865 957 958 Promise.prototype.isFulfilled = function () { 959 return this.inspect().state === "fulfilled"; 960 }; 961 866 962 /** 867 963 * @returns whether the given object is a rejected promise. … … 871 967 return isPromise(object) && object.inspect().state === "rejected"; 872 968 } 969 970 Promise.prototype.isRejected = function () { 971 return this.inspect().state === "rejected"; 972 }; 873 973 874 974 //// BEGIN UNHANDLED REJECTION TRACKING … … 899 999 for (var i = 0; i < unhandledReasons.length; i++) { 900 1000 var reason = unhandledReasons[i]; 901 if (reason && typeof reason.stack !== "undefined") { 902 console.warn("Unhandled rejection reason:", reason.stack); 903 } else { 904 console.warn("Unhandled rejection reason (no stack):", reason); 905 } 1001 console.warn("Unhandled rejection reason:", reason); 906 1002 } 907 1003 } … … 930 1026 931 1027 unhandledRejections.push(promise); 932 unhandledReasons.push(reason); 1028 if (reason && typeof reason.stack !== "undefined") { 1029 unhandledReasons.push(reason.stack); 1030 } else { 1031 unhandledReasons.push("(no stack) " + reason); 1032 } 933 1033 displayUnhandledReasons(); 934 1034 } … … 1019 1119 } 1020 1120 }, 1021 "apply": function (this P, args) {1022 return value.apply(this P, args);1121 "apply": function (thisp, args) { 1122 return value.apply(thisp, args); 1023 1123 }, 1024 1124 "keys": function () { … … 1028 1128 return { state: "fulfilled", value: value }; 1029 1129 }); 1030 }1031 1032 /**1033 * Constructs a promise for an immediate reference, passes promises through, or1034 * coerces promises from different systems.1035 * @param value immediate reference or promise1036 */1037 Q.resolve = resolve;1038 function resolve(value) {1039 // If the object is already a Promise, return it directly. This enables1040 // the resolve function to both be used to created references from objects,1041 // but to tolerably coerce non-promises to promises.1042 if (isPromise(value)) {1043 return value;1044 }1045 1046 // assimilate thenables1047 if (isPromiseAlike(value)) {1048 return coerce(value);1049 } else {1050 return fulfill(value);1051 }1052 1130 } 1053 1131 … … 1085 1163 return dispatch(object, op, args); 1086 1164 }, function () { 1087 return resolve(object).inspect();1165 return Q(object).inspect(); 1088 1166 }); 1089 }1090 1091 /**1092 * Registers an observer on a promise.1093 *1094 * Guarantees:1095 *1096 * 1. that fulfilled and rejected will be called only once.1097 * 2. that either the fulfilled callback or the rejected callback will be1098 * called, but not both.1099 * 3. that fulfilled and rejected will not be called in this turn.1100 *1101 * @param value promise or immediate reference to observe1102 * @param fulfilled function to be called with the fulfilled value1103 * @param rejected function to be called with the rejection exception1104 * @param progressed function to be called on any progress notifications1105 * @return promise for the return value from the invoked callback1106 */1107 Q.when = when;1108 function when(value, fulfilled, rejected, progressed) {1109 return Q(value).then(fulfilled, rejected, progressed);1110 1167 } 1111 1168 … … 1121 1178 */ 1122 1179 Q.spread = spread; 1123 function spread(promise, fulfilled, rejected) { 1124 return when(promise, function (valuesOrPromises) { 1125 return all(valuesOrPromises).then(function (values) { 1126 return fulfilled.apply(void 0, values); 1127 }, rejected); 1180 function spread(value, fulfilled, rejected) { 1181 return Q(value).spread(fulfilled, rejected); 1182 } 1183 1184 Promise.prototype.spread = function (fulfilled, rejected) { 1185 return this.all().then(function (array) { 1186 return fulfilled.apply(void 0, array); 1128 1187 }, rejected); 1129 } 1188 }; 1130 1189 1131 1190 /** … … 1188 1247 } 1189 1248 var generator = makeGenerator.apply(this, arguments); 1190 var callback = continuer.bind(continuer, " send");1249 var callback = continuer.bind(continuer, "next"); 1191 1250 var errback = continuer.bind(continuer, "throw"); 1192 1251 return callback(); … … 1246 1305 * return a + b; 1247 1306 * }); 1248 * add(Q .resolve(a), Q.resolve(B));1307 * add(Q(a), Q(B)); 1249 1308 * 1250 1309 * @param {function} callback The function to decorate … … 1269 1328 Q.dispatch = dispatch; 1270 1329 function dispatch(object, op, args) { 1330 return Q(object).dispatch(op, args); 1331 } 1332 1333 Promise.prototype.dispatch = function (op, args) { 1334 var self = this; 1271 1335 var deferred = defer(); 1272 1336 nextTick(function () { 1273 resolve(object).promiseDispatch(deferred.resolve, op, args);1337 self.promiseDispatch(deferred.resolve, op, args); 1274 1338 }); 1275 1339 return deferred.promise; 1276 } 1277 1278 /** 1279 * Constructs a promise method that can be used to safely observe resolution of 1280 * a promise for an arbitrarily named method like "propfind" in a future turn. 1281 * 1282 * "dispatcher" constructs methods like "get(promise, name)" and "set(promise)". 1283 */ 1284 Q.dispatcher = dispatcher; 1285 function dispatcher(op) { 1286 return function (object) { 1287 var args = array_slice(arguments, 1); 1288 return dispatch(object, op, args); 1289 }; 1290 } 1340 }; 1291 1341 1292 1342 /** … … 1296 1346 * @return promise for the property value 1297 1347 */ 1298 Q.get = dispatcher("get"); 1348 Q.get = function (object, key) { 1349 return Q(object).dispatch("get", [key]); 1350 }; 1351 1352 Promise.prototype.get = function (key) { 1353 return this.dispatch("get", [key]); 1354 }; 1299 1355 1300 1356 /** … … 1305 1361 * @return promise for the return value 1306 1362 */ 1307 Q.set = dispatcher("set"); 1363 Q.set = function (object, key, value) { 1364 return Q(object).dispatch("set", [key, value]); 1365 }; 1366 1367 Promise.prototype.set = function (key, value) { 1368 return this.dispatch("set", [key, value]); 1369 }; 1308 1370 1309 1371 /** … … 1313 1375 * @return promise for the return value 1314 1376 */ 1315 Q["delete"] = // XXX experimental 1316 Q.del = dispatcher("delete"); 1377 Q.del = // XXX legacy 1378 Q["delete"] = function (object, key) { 1379 return Q(object).dispatch("delete", [key]); 1380 }; 1381 1382 Promise.prototype.del = // XXX legacy 1383 Promise.prototype["delete"] = function (key) { 1384 return this.dispatch("delete", [key]); 1385 }; 1317 1386 1318 1387 /** … … 1329 1398 */ 1330 1399 // bound locally because it is used by other methods 1331 var post = Q.post = dispatcher("post"); 1332 Q.mapply = post; // experimental 1400 Q.mapply = // XXX As proposed by "Redsandro" 1401 Q.post = function (object, name, args) { 1402 return Q(object).dispatch("post", [name, args]); 1403 }; 1404 1405 Promise.prototype.mapply = // XXX As proposed by "Redsandro" 1406 Promise.prototype.post = function (name, args) { 1407 return this.dispatch("post", [name, args]); 1408 }; 1333 1409 1334 1410 /** … … 1339 1415 * @return promise for the return value 1340 1416 */ 1341 Q.send = send; 1342 Q.invoke = send; // synonyms 1343 Q.mcall = send; // experimental 1344 function send(value, name) { 1345 var args = array_slice(arguments, 2); 1346 return post(value, name, args); 1347 } 1417 Q.send = // XXX Mark Miller's proposed parlance 1418 Q.mcall = // XXX As proposed by "Redsandro" 1419 Q.invoke = function (object, name /*...args*/) { 1420 return Q(object).dispatch("post", [name, array_slice(arguments, 2)]); 1421 }; 1422 1423 Promise.prototype.send = // XXX Mark Miller's proposed parlance 1424 Promise.prototype.mcall = // XXX As proposed by "Redsandro" 1425 Promise.prototype.invoke = function (name /*...args*/) { 1426 return this.dispatch("post", [name, array_slice(arguments, 1)]); 1427 }; 1348 1428 1349 1429 /** … … 1352 1432 * @param args array of application arguments 1353 1433 */ 1354 Q.fapply = fapply; 1355 function fapply(value, args) { 1356 return dispatch(value, "apply", [void 0, args]); 1357 } 1434 Q.fapply = function (object, args) { 1435 return Q(object).dispatch("apply", [void 0, args]); 1436 }; 1437 1438 Promise.prototype.fapply = function (args) { 1439 return this.dispatch("apply", [void 0, args]); 1440 }; 1358 1441 1359 1442 /** … … 1362 1445 * @param ...args array of application arguments 1363 1446 */ 1364 Q["try"] = fcall; // XXX experimental 1365 Q.fcall = fcall; 1366 function fcall(value) { 1367 var args = array_slice(arguments, 1); 1368 return fapply(value, args); 1369 } 1447 Q["try"] = 1448 Q.fcall = function (object /* ...args*/) { 1449 return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]); 1450 }; 1451 1452 Promise.prototype.fcall = function (/*...args*/) { 1453 return this.dispatch("apply", [void 0, array_slice(arguments)]); 1454 }; 1370 1455 1371 1456 /** … … 1375 1460 * @param ...args array of application arguments 1376 1461 */ 1377 Q.fbind = f bind;1378 function fbind(value) { 1462 Q.fbind = function (object /*...args*/) { 1463 var promise = Q(object); 1379 1464 var args = array_slice(arguments, 1); 1380 1465 return function fbound() { 1381 var allArgs = args.concat(array_slice(arguments)); 1382 return dispatch(value, "apply", [this, allArgs]); 1466 return promise.dispatch("apply", [ 1467 this, 1468 args.concat(array_slice(arguments)) 1469 ]); 1383 1470 }; 1384 } 1471 }; 1472 Promise.prototype.fbind = function (/*...args*/) { 1473 var promise = this; 1474 var args = array_slice(arguments); 1475 return function fbound() { 1476 return promise.dispatch("apply", [ 1477 this, 1478 args.concat(array_slice(arguments)) 1479 ]); 1480 }; 1481 }; 1385 1482 1386 1483 /** … … 1390 1487 * @return promise for the keys of the eventually settled object 1391 1488 */ 1392 Q.keys = dispatcher("keys"); 1489 Q.keys = function (object) { 1490 return Q(object).dispatch("keys", []); 1491 }; 1492 1493 Promise.prototype.keys = function () { 1494 return this.dispatch("keys", []); 1495 }; 1393 1496 1394 1497 /** … … 1415 1518 } else { 1416 1519 ++countDown; 1417 when(promise, function (value) { 1418 promises[index] = value; 1419 if (--countDown === 0) { 1420 deferred.resolve(promises); 1520 when( 1521 promise, 1522 function (value) { 1523 promises[index] = value; 1524 if (--countDown === 0) { 1525 deferred.resolve(promises); 1526 } 1527 }, 1528 deferred.reject, 1529 function (progress) { 1530 deferred.notify({ index: index, value: progress }); 1421 1531 } 1422 }, deferred.reject);1532 ); 1423 1533 } 1424 1534 }, void 0); … … 1429 1539 }); 1430 1540 } 1541 1542 Promise.prototype.all = function () { 1543 return all(this); 1544 }; 1431 1545 1432 1546 /** … … 1442 1556 function allResolved(promises) { 1443 1557 return when(promises, function (promises) { 1444 promises = array_map(promises, resolve);1558 promises = array_map(promises, Q); 1445 1559 return when(all(array_map(promises, function (promise) { 1446 1560 return when(promise, noop, noop); … … 1451 1565 } 1452 1566 1567 Promise.prototype.allResolved = function () { 1568 return allResolved(this); 1569 }; 1570 1571 /** 1572 * @see Promise#allSettled 1573 */ 1453 1574 Q.allSettled = allSettled; 1454 function allSettled(values) { 1455 return when(values, function (values) { 1456 return all(array_map(values, function (value, i) { 1457 return when( 1458 value, 1459 function (fulfillmentValue) { 1460 values[i] = { state: "fulfilled", value: fulfillmentValue }; 1461 return values[i]; 1462 }, 1463 function (reason) { 1464 values[i] = { state: "rejected", reason: reason }; 1465 return values[i]; 1466 } 1467 ); 1468 })).thenResolve(values); 1575 function allSettled(promises) { 1576 return Q(promises).allSettled(); 1577 } 1578 1579 /** 1580 * Turns an array of promises into a promise for an array of their states (as 1581 * returned by `inspect`) when they have all settled. 1582 * @param {Array[Any*]} values an array (or promise for an array) of values (or 1583 * promises for values) 1584 * @returns {Array[State]} an array of states for the respective values. 1585 */ 1586 Promise.prototype.allSettled = function () { 1587 return this.then(function (promises) { 1588 return all(array_map(promises, function (promise) { 1589 promise = Q(promise); 1590 function regardless() { 1591 return promise.inspect(); 1592 } 1593 return promise.then(regardless, regardless); 1594 })); 1469 1595 }); 1470 } 1596 }; 1471 1597 1472 1598 /** … … 1479 1605 * @returns a promise for the return value of the callback 1480 1606 */ 1481 Q["catch"] = // XXX experimental 1482 Q.fail = fail; 1483 function fail(promise, rejected) { 1484 return when(promise, void 0, rejected); 1485 } 1607 Q.fail = // XXX legacy 1608 Q["catch"] = function (object, rejected) { 1609 return Q(object).then(void 0, rejected); 1610 }; 1611 1612 Promise.prototype.fail = // XXX legacy 1613 Promise.prototype["catch"] = function (rejected) { 1614 return this.then(void 0, rejected); 1615 }; 1486 1616 1487 1617 /** … … 1494 1624 */ 1495 1625 Q.progress = progress; 1496 function progress(promise, progressed) { 1497 return when(promise, void 0, void 0, progressed); 1498 } 1626 function progress(object, progressed) { 1627 return Q(object).then(void 0, void 0, progressed); 1628 } 1629 1630 Promise.prototype.progress = function (progressed) { 1631 return this.then(void 0, void 0, progressed); 1632 }; 1499 1633 1500 1634 /** … … 1509 1643 * ``fin`` is done. 1510 1644 */ 1511 Q["finally"] = // XXX experimental 1512 Q.fin = fin; 1513 function fin(promise, callback) { 1514 return when(promise, function (value) { 1515 return when(callback(), function () { 1645 Q.fin = // XXX legacy 1646 Q["finally"] = function (object, callback) { 1647 return Q(object)["finally"](callback); 1648 }; 1649 1650 Promise.prototype.fin = // XXX legacy 1651 Promise.prototype["finally"] = function (callback) { 1652 callback = Q(callback); 1653 return this.then(function (value) { 1654 return callback.fcall().then(function () { 1516 1655 return value; 1517 1656 }); 1518 }, function (exception) { 1519 return when(callback(), function () { 1520 return reject(exception); 1657 }, function (reason) { 1658 // TODO attempt to recycle the rejection with "this". 1659 return callback.fcall().then(function () { 1660 throw reason; 1521 1661 }); 1522 1662 }); 1523 } 1663 }; 1524 1664 1525 1665 /** … … 1529 1669 * @returns nothing 1530 1670 */ 1531 Q.done = done; 1532 function done(promise, fulfilled, rejected, progress) { 1671 Q.done = function (object, fulfilled, rejected, progress) { 1672 return Q(object).done(fulfilled, rejected, progress); 1673 }; 1674 1675 Promise.prototype.done = function (fulfilled, rejected, progress) { 1533 1676 var onUnhandledError = function (error) { 1534 1677 // forward to a future turn so that ``when`` … … 1536 1679 nextTick(function () { 1537 1680 makeStackTraceLong(error, promise); 1538 1539 1681 if (Q.onerror) { 1540 1682 Q.onerror(error); … … 1546 1688 1547 1689 // Avoid unnecessary `nextTick`ing via an unnecessary `when`. 1548 var promise ToHandle= fulfilled || rejected || progress ?1549 when(promise,fulfilled, rejected, progress) :1550 promise;1690 var promise = fulfilled || rejected || progress ? 1691 this.then(fulfilled, rejected, progress) : 1692 this; 1551 1693 1552 1694 if (typeof process === "object" && process && process.domain) { 1553 1695 onUnhandledError = process.domain.bind(onUnhandledError); 1554 1696 } 1555 fail(promiseToHandle, onUnhandledError); 1556 } 1697 1698 promise.then(void 0, onUnhandledError); 1699 }; 1557 1700 1558 1701 /** … … 1565 1708 * fulfilled before the timeout, otherwise rejected. 1566 1709 */ 1567 Q.timeout = timeout; 1568 function timeout(promise, ms, msg) { 1710 Q.timeout = function (object, ms, message) { 1711 return Q(object).timeout(ms, message); 1712 }; 1713 1714 Promise.prototype.timeout = function (ms, message) { 1569 1715 var deferred = defer(); 1570 1716 var timeoutId = setTimeout(function () { 1571 deferred.reject(new Error(m sg|| "Timed out after " + ms + " ms"));1717 deferred.reject(new Error(message || "Timed out after " + ms + " ms")); 1572 1718 }, ms); 1573 1719 1574 when(promise,function (value) {1720 this.then(function (value) { 1575 1721 clearTimeout(timeoutId); 1576 1722 deferred.resolve(value); … … 1581 1727 1582 1728 return deferred.promise; 1583 } 1584 1585 /** 1586 * Returns a promise for the given value (or promised value) aftersome1587 * milliseconds .1729 }; 1730 1731 /** 1732 * Returns a promise for the given value (or promised value), some 1733 * milliseconds after it resolved. Passes rejections immediately. 1588 1734 * @param {Any*} promise 1589 1735 * @param {Number} milliseconds 1590 * @returns a promise for the resolution of the given promise after some1591 * time has elapsed .1592 * /1593 Q.delay = delay; 1594 function delay(promise, timeout) {1736 * @returns a promise for the resolution of the given promise after milliseconds 1737 * time has elapsed since the resolution of the given promise. 1738 * If the given promise rejects, that is passed immediately. 1739 */ 1740 Q.delay = function (object, timeout) { 1595 1741 if (timeout === void 0) { 1596 timeout = promise; 1597 promise = void 0; 1598 } 1599 1600 var deferred = defer(); 1601 1602 when(promise, undefined, undefined, deferred.notify); 1603 setTimeout(function () { 1604 deferred.resolve(promise); 1605 }, timeout); 1606 1607 return deferred.promise; 1608 } 1742 timeout = object; 1743 object = void 0; 1744 } 1745 return Q(object).delay(timeout); 1746 }; 1747 1748 Promise.prototype.delay = function (timeout) { 1749 return this.then(function (value) { 1750 var deferred = defer(); 1751 setTimeout(function () { 1752 deferred.resolve(value); 1753 }, timeout); 1754 return deferred.promise; 1755 }); 1756 }; 1609 1757 1610 1758 /** … … 1617 1765 * 1618 1766 */ 1619 Q.nfapply = nfapply; 1620 function nfapply(callback, args) { 1767 Q.nfapply = function (callback, args) { 1768 return Q(callback).nfapply(args); 1769 }; 1770 1771 Promise.prototype.nfapply = function (args) { 1772 var deferred = defer(); 1621 1773 var nodeArgs = array_slice(args); 1774 nodeArgs.push(deferred.makeNodeResolver()); 1775 this.fapply(nodeArgs).fail(deferred.reject); 1776 return deferred.promise; 1777 }; 1778 1779 /** 1780 * Passes a continuation to a Node function, which is called with the given 1781 * arguments provided individually, and returns a promise. 1782 * @example 1783 * Q.nfcall(FS.readFile, __filename) 1784 * .then(function (content) { 1785 * }) 1786 * 1787 */ 1788 Q.nfcall = function (callback /*...args*/) { 1789 var args = array_slice(arguments, 1); 1790 return Q(callback).nfapply(args); 1791 }; 1792 1793 Promise.prototype.nfcall = function (/*...args*/) { 1794 var nodeArgs = array_slice(arguments); 1622 1795 var deferred = defer(); 1623 1796 nodeArgs.push(deferred.makeNodeResolver()); 1624 1625 fapply(callback, nodeArgs).fail(deferred.reject); 1797 this.fapply(nodeArgs).fail(deferred.reject); 1626 1798 return deferred.promise; 1627 } 1628 1629 /** 1630 * Passes a continuation to a Node function, which is called with the given 1631 * arguments provided individually, and returns a promise. 1632 * 1633 * Q.nfcall(FS.readFile, __filename) 1634 * .then(function (content) { 1635 * }) 1636 * 1637 */ 1638 Q.nfcall = nfcall; 1639 function nfcall(callback/*, ...args */) { 1640 var nodeArgs = array_slice(arguments, 1); 1641 var deferred = defer(); 1642 nodeArgs.push(deferred.makeNodeResolver()); 1643 1644 fapply(callback, nodeArgs).fail(deferred.reject); 1645 return deferred.promise; 1646 } 1799 }; 1647 1800 1648 1801 /** 1649 1802 * Wraps a NodeJS continuation passing function and returns an equivalent 1650 1803 * version that returns a promise. 1651 * 1652 * Q.nfbind(FS.readFile, __filename)("utf-8") 1653 * .then(console.log) 1654 * .done() 1655 * 1656 */ 1657 Q.nfbind = nfbind; 1658 Q.denodeify = Q.nfbind; // synonyms 1659 function nfbind(callback/*, ...args */) { 1804 * @example 1805 * Q.nfbind(FS.readFile, __filename)("utf-8") 1806 * .then(console.log) 1807 * .done() 1808 */ 1809 Q.nfbind = 1810 Q.denodeify = function (callback /*...args*/) { 1660 1811 var baseArgs = array_slice(arguments, 1); 1661 1812 return function () { … … 1663 1814 var deferred = defer(); 1664 1815 nodeArgs.push(deferred.makeNodeResolver()); 1665 1666 fapply(callback, nodeArgs).fail(deferred.reject); 1816 Q(callback).fapply(nodeArgs).fail(deferred.reject); 1667 1817 return deferred.promise; 1668 1818 }; 1669 } 1670 1671 Q.nbind = nbind; 1672 function nbind(callback, thisArg /*, ... args*/) { 1819 }; 1820 1821 Promise.prototype.nfbind = 1822 Promise.prototype.denodeify = function (/*...args*/) { 1823 var args = array_slice(arguments); 1824 args.unshift(this); 1825 return Q.denodeify.apply(void 0, args); 1826 }; 1827 1828 Q.nbind = function (callback, thisp /*...args*/) { 1673 1829 var baseArgs = array_slice(arguments, 2); 1674 1830 return function () { … … 1676 1832 var deferred = defer(); 1677 1833 nodeArgs.push(deferred.makeNodeResolver()); 1678 1679 1834 function bound() { 1680 return callback.apply(thisArg, arguments); 1681 } 1682 1683 fapply(bound, nodeArgs).fail(deferred.reject); 1835 return callback.apply(thisp, arguments); 1836 } 1837 Q(bound).fapply(nodeArgs).fail(deferred.reject); 1684 1838 return deferred.promise; 1685 1839 }; 1686 } 1840 }; 1841 1842 Promise.prototype.nbind = function (/*thisp, ...args*/) { 1843 var args = array_slice(arguments, 0); 1844 args.unshift(this); 1845 return Q.nbind.apply(void 0, args); 1846 }; 1687 1847 1688 1848 /** … … 1695 1855 * @returns a promise for the value or error 1696 1856 */ 1697 Q.npost = npost; 1698 Q.nmapply = npost; // synonyms 1699 function npost(object, name, args) { 1857 Q.nmapply = // XXX As proposed by "Redsandro" 1858 Q.npost = function (object, name, args) { 1859 return Q(object).npost(name, args); 1860 }; 1861 1862 Promise.prototype.nmapply = // XXX As proposed by "Redsandro" 1863 Promise.prototype.npost = function (name, args) { 1700 1864 var nodeArgs = array_slice(args || []); 1701 1865 var deferred = defer(); 1702 1866 nodeArgs.push(deferred.makeNodeResolver()); 1703 1704 post(object, name, nodeArgs).fail(deferred.reject); 1867 this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); 1705 1868 return deferred.promise; 1706 } 1869 }; 1707 1870 1708 1871 /** … … 1716 1879 * @returns a promise for the value or error 1717 1880 */ 1718 Q.nsend = nsend; 1719 Q.ninvoke = Q.nsend; // synonyms 1720 Q.nmcall = Q.nsend; // synonyms 1721 function nsend(object, name /*, ...args*/) { 1881 Q.nsend = // XXX Based on Mark Miller's proposed "send" 1882 Q.nmcall = // XXX Based on "Redsandro's" proposal 1883 Q.ninvoke = function (object, name /*...args*/) { 1722 1884 var nodeArgs = array_slice(arguments, 2); 1723 1885 var deferred = defer(); 1724 1886 nodeArgs.push(deferred.makeNodeResolver()); 1725 post(object, name, nodeArgs).fail(deferred.reject);1887 Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject); 1726 1888 return deferred.promise; 1727 } 1728 1889 }; 1890 1891 Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send" 1892 Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal 1893 Promise.prototype.ninvoke = function (name /*...args*/) { 1894 var nodeArgs = array_slice(arguments, 1); 1895 var deferred = defer(); 1896 nodeArgs.push(deferred.makeNodeResolver()); 1897 this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); 1898 return deferred.promise; 1899 }; 1900 1901 /** 1902 * If a function would like to support both Node continuation-passing-style and 1903 * promise-returning-style, it can end its internal promise chain with 1904 * `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user 1905 * elects to use a nodeback, the result will be sent there. If they do not 1906 * pass a nodeback, they will receive the result promise. 1907 * @param object a result (or a promise for a result) 1908 * @param {Function} nodeback a Node.js-style callback 1909 * @returns either the promise or nothing 1910 */ 1729 1911 Q.nodeify = nodeify; 1730 function nodeify(promise, nodeback) { 1912 function nodeify(object, nodeback) { 1913 return Q(object).nodeify(nodeback); 1914 } 1915 1916 Promise.prototype.nodeify = function (nodeback) { 1731 1917 if (nodeback) { 1732 promise.then(function (value) {1918 this.then(function (value) { 1733 1919 nextTick(function () { 1734 1920 nodeback(null, value); … … 1740 1926 }); 1741 1927 } else { 1742 return promise;1743 } 1744 } 1928 return this; 1929 } 1930 }; 1745 1931 1746 1932 // All code before this point will be filtered from stack traces.
Note: See TracChangeset
for help on using the changeset viewer.