{"id":8195,"date":"2019-05-01T04:39:00","date_gmt":"2019-05-01T04:39:00","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/12\/01\/kriskowal-q\/"},"modified":"2022-08-30T15:22:23","modified_gmt":"2022-08-30T15:22:23","slug":"kriskowal-q","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2019\/05\/01\/kriskowal-q\/","title":{"rendered":"kriskowal\/q"},"content":{"rendered":"<p><img decoding=\"async\" src=\"http:\/\/secure.travis-ci.org\/kriskowal\/q.png?branch=master\"><\/p>\n<p><img decoding=\"async\" src=\"http:\/\/kriskowal.github.io\/q\/q.png\"><\/p>\n<p><em>This is Q version 1, from the <code>v1<\/code> branch in Git. This documentation applies to the latest of both the version 1 and version 0.9 release trains. These releases are stable. There will be no further releases of 0.9 after 0.9.7 which is nearly equivalent to version 1.0.0. All further releases of <code>q@~1.0<\/code> will be backward compatible. The version 2 release train introduces significant and backward-incompatible changes and is experimental at this time.<\/em><\/p>\n<p>If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.<\/p>\n<p>On the first pass, promises can mitigate the \u201cPyramid of Doom\u201d: the situation where code marches to the right faster than it marches forward.<\/p>\n<pre><code>step1(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<\/code><\/pre>\n<p>With a promise library, you can flatten the pyramid.<\/p>\n<pre><code>Q.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<\/code><\/pre>\n<p>With this approach, you also get implicit error propagation, just like <code>try<\/code>, <code>catch<\/code>, and <code>finally<\/code>. An error in <code>promisedStep1<\/code> will flow all the way to the <code>catch<\/code> function, where it\u2019s caught and handled. (Here <code>promisedStepN<\/code> is a version of <code>stepN<\/code> that returns a promise.)<\/p>\n<p>The callback approach is called an \u201cinversion of control\u201d. A function that accepts a callback instead of a return value is saying, \u201cDon\u2019t call me, I\u2019ll call you.\u201d. Promises un-invert the inversion, cleanly separating the input arguments from control flow arguments. This simplifies the use and creation of API\u2019s, particularly variadic, rest and spread arguments.<\/p>\n<h2>Getting Started<\/h2>\n<p>The Q module can be loaded as:<\/p>\n<ul>\n<li>A tag (creating a <code>Q<\/code> global variable): ~2.5 KB minified and gzipped.<\/li>\n<li>A Node.js and CommonJS module, available in npm as the q package<\/li>\n<li>An AMD module<\/li>\n<li>A component as <code>microjs\/q<\/code><\/li>\n<li>Using bower as <code>q#1.0.1<\/code><\/li>\n<li>Using NuGet as Q<\/li>\n<\/ul>\n<p>Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more.<\/p>\n<h2>Resources<\/h2>\n<p>Our wiki contains a number of useful resources, including:<\/p>\n<ul>\n<li>A method-by-method Q API reference.<\/li>\n<li>A growing examples gallery, showing how Q can be used to make everything better. From XHR to database access to accessing the Flickr API, Q is there for you.<\/li>\n<li>There are many libraries that produce and consume Q promises for everything from file system\/database access or RPC to templating. For a list of some of the more popular ones, see Libraries.<\/li>\n<li>If you want materials that introduce the promise concept generally, and the below tutorial isn\u2019t doing it for you, check out our collection of presentations, blog posts, and podcasts.<\/li>\n<li>A guide for those coming from jQuery\u2019s <code>$.Deferred<\/code>.<\/li>\n<\/ul>\n<p>We\u2019d also love to have you join the Q-Continuum mailing list.<\/p>\n<h2>Tutorial<\/h2>\n<p>Promises have a <code>then<\/code> method, which you can use to get the eventual return value (fulfillment) or thrown exception (rejection).<\/p>\n<pre><code>promiseMeSomething()\n.then(function (value) {\n}, function (reason) {\n});\n<\/code><\/pre>\n<p>If <code>promiseMeSomething<\/code> returns a promise that gets fulfilled later with a return value, the first function (the fulfillment handler) will be called with the value. However, if the <code>promiseMeSomething<\/code> function gets rejected later by a thrown exception, the second function (the rejection handler) will be called with the exception.<\/p>\n<p>Note that resolution of a promise is always asynchronous: that is, the fulfillment or rejection handler will always be called in the next turn of the event loop (i.e. <code>process.nextTick<\/code> in Node). This gives you a nice guarantee when mentally tracing the flow of your code, namely that <code>then<\/code> will always return before either handler is executed.<\/p>\n<p>In this tutorial, we begin with how to consume and work with promises. We\u2019ll talk about how to create them, and thus create functions like <code>promiseMeSomething<\/code> that return promises, below.<\/p>\n<h3>Propagation<\/h3>\n<p>The <code>then<\/code> method returns a promise, which in this example, I\u2019m assigning to <code>outputPromise<\/code>.<\/p>\n<pre><code>var outputPromise = getInputPromise()\n.then(function (input) {\n}, function (reason) {\n});\n<\/code><\/pre>\n<p>The <code>outputPromise<\/code> variable becomes a new promise for the return value of either handler. Since a function can only either return a value or throw an exception, only one handler will ever be called and it will be responsible for resolving <code>outputPromise<\/code>.<\/p>\n<ul>\n<li>If you return a value in a handler, <code>outputPromise<\/code> will get fulfilled.<\/li>\n<li>If you throw an exception in a handler, <code>outputPromise<\/code> will get rejected.<\/li>\n<li>If you return a <strong>promise<\/strong> in a handler, <code>outputPromise<\/code> will \u201cbecome\u201d that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.<\/li>\n<\/ul>\n<p>If the <code>getInputPromise()<\/code> promise gets rejected and you omit the rejection handler, the <strong>error<\/strong> will go to <code>outputPromise<\/code>:<\/p>\n<pre><code>var outputPromise = getInputPromise()\n.then(function (value) {\n});\n<\/code><\/pre>\n<p>If the input promise gets fulfilled and you omit the fulfillment handler, the <strong>value<\/strong> will go to <code>outputPromise<\/code>:<\/p>\n<pre><code>var outputPromise = getInputPromise()\n.then(null, function (error) {\n});\n<\/code><\/pre>\n<p>Q promises provide a <code>fail<\/code> shorthand for <code>then<\/code> when you are only interested in handling the error:<\/p>\n<pre><code>var outputPromise = getInputPromise()\n.fail(function (error) {\n});\n<\/code><\/pre>\n<p>If you are writing JavaScript for modern engines only or using CoffeeScript, you may use <code>catch<\/code> instead of <code>fail<\/code>.<\/p>\n<p>Promises also have a <code>fin<\/code> function that is like a <code>finally<\/code> clause. The final handler gets called, with no arguments, when the promise returned by <code>getInputPromise()<\/code> either returns a value or throws an error. The value returned or error thrown by <code>getInputPromise()<\/code> passes directly to <code>outputPromise<\/code> unless the final handler fails, and may be delayed if the final handler returns a promise.<\/p>\n<pre><code>var outputPromise = getInputPromise()\n.fin(function () {\n    \/\/ close files, database connections, stop servers, conclude tests\n});\n<\/code><\/pre>\n<ul>\n<li>If the handler returns a value, the value is ignored<\/li>\n<li>If the handler throws an error, the error passes to <code>outputPromise<\/code><\/li>\n<li>If the handler returns a promise, <code>outputPromise<\/code> gets postponed. The eventual value or error has the same effect as an immediate return value or thrown error: a value would be ignored, an error would be forwarded.<\/li>\n<\/ul>\n<p>If you are writing JavaScript for modern engines only or using CoffeeScript, you may use <code>finally<\/code> instead of <code>fin<\/code>.<\/p>\n<h3>Chaining<\/h3>\n<p>There are two ways to chain promises. You can chain promises either inside or outside handlers. The next two examples are equivalent.<\/p>\n<pre><code>return 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<\/code><\/pre>\n<pre><code>return 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<\/code><\/pre>\n<p>The only difference is nesting. It\u2019s useful to nest handlers if you need to capture multiple input values in your closure.<\/p>\n<pre><code>function 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<\/code><\/pre>\n<h3>Combination<\/h3>\n<p>You can turn an array of promises into a promise for the whole, fulfilled array using <code>all<\/code>.<\/p>\n<pre><code>return Q.all([\n    eventualAdd(2, 2),\n    eventualAdd(10, 20)\n]);\n<\/code><\/pre>\n<p>If you have a promise for an array, you can use <code>spread<\/code> as a replacement for <code>then<\/code>. The <code>spread<\/code> function \u201cspreads\u201d the values over the arguments of the fulfillment handler. The rejection handler will get called at the first sign of failure. That is, whichever of the received promises fails first gets handled by the rejection handler.<\/p>\n<pre><code>function eventualAdd(a, b) {\n    return Q.spread([a, b], function (a, b) {\n        return a + b;\n    })\n}\n<\/code><\/pre>\n<p>But <code>spread<\/code> calls <code>all<\/code> initially, so you can skip it in chains.<\/p>\n<pre><code>return getUsername()\n.then(function (username) {\n    return [username, getUser(username)];\n})\n.spread(function (username, user) {\n});\n<\/code><\/pre>\n<p>The <code>all<\/code> function returns a promise for an array of values. When this promise is fulfilled, the array contains the fulfillment values of the original promises, in the same order as those promises. If one of the given promises is rejected, the returned promise is immediately rejected, not waiting for the rest of the batch. If you want to wait for all of the promises to either be fulfilled or rejected, you can use <code>allSettled<\/code>.<\/p>\n<pre><code>Q.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<\/code><\/pre>\n<p>The <code>any<\/code> function accepts an array of promises and returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected if all of the given promises are rejected.<\/p>\n<pre><code>Q.any(promises)\n.then(function (first) {\n    \/\/ Any of the promises was fulfilled.\n}, function (error) {\n    \/\/ All of the promises were rejected.\n});\n<\/code><\/pre>\n<h3>Sequences<\/h3>\n<p>If you have a number of promise-producing functions that need to be run sequentially, you can of course do so manually:<\/p>\n<pre><code>return foo(initialVal).then(bar).then(baz).then(qux);\n<\/code><\/pre>\n<p>However, if you want to run a dynamically constructed sequence of functions, you\u2019ll want something like this:<\/p>\n<pre><code>var funcs = [foo, bar, baz, qux];\n\nvar result = Q(initialVal);\nfuncs.forEach(function (f) {\n    result = result.then(f);\n});\nreturn result;\n<\/code><\/pre>\n<p>You can make this slightly more compact using <code>reduce<\/code>:<\/p>\n<pre><code>return funcs.reduce(function (soFar, f) {\n    return soFar.then(f);\n}, Q(initialVal));\n<\/code><\/pre>\n<p>Or, you could use the ultra-compact version:<\/p>\n<pre><code>return funcs.reduce(Q.when, Q(initialVal));\n<\/code><\/pre>\n<h3>Handling Errors<\/h3>\n<p>One sometimes-unintuive aspect of promises is that if you throw an exception in the fulfillment handler, it will not be caught by the error handler.<\/p>\n<pre><code>return 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<\/code><\/pre>\n<p>To see why this is, consider the parallel between promises and <code>try<\/code>\/<code>catch<\/code>. We are <code>try<\/code>-ing to execute <code>foo()<\/code>: the error handler represents a <code>catch<\/code> for <code>foo()<\/code>, while the fulfillment handler represents code that happens <em>after<\/em> the <code>try<\/code>\/<code>catch<\/code> block. That code then needs its own <code>try<\/code>\/<code>catch<\/code> block.<\/p>\n<p>In terms of promises, this means chaining your rejection handler:<\/p>\n<pre><code>return 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<\/code><\/pre>\n<h3>Progress Notification<\/h3>\n<p>It\u2019s possible for promises to report their progress, e.g. for tasks that take a long time like a file upload. Not all promises will implement progress notifications, but for those that do, you can consume the progress values using a third parameter to <code>then<\/code>:<\/p>\n<pre><code>return 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<\/code><\/pre>\n<p>Like <code>fail<\/code>, Q also provides a shorthand for progress callbacks called <code>progress<\/code>:<\/p>\n<pre><code>return uploadFile().progress(function (progress) {\n    \/\/ We get notified of the upload's progress\n});\n<\/code><\/pre>\n<h3>The End<\/h3>\n<p>When you get to the end of a chain of promises, you should either return the last promise or end the chain. Since handlers catch errors, it\u2019s an unfortunate pattern that the exceptions can go unobserved.<\/p>\n<p>So, either return it,<\/p>\n<pre><code>return foo()\n.then(function () {\n    return \"bar\";\n});\n<\/code><\/pre>\n<p>Or, end it.<\/p>\n<pre><code>foo()\n.then(function () {\n    return \"bar\";\n})\n.done();\n<\/code><\/pre>\n<p>Ending a promise chain makes sure that, if an error doesn\u2019t get handled before the end, it will get rethrown and reported.<\/p>\n<p>This is a stopgap. We are exploring ways to make unhandled errors visible without any explicit handling.<\/p>\n<h3>The Beginning<\/h3>\n<p>Everything above assumes you get a promise from somewhere else. This is the common case. Every once in a while, you will need to create a promise from scratch.<\/p>\n<h4>Using <code>Q.fcall<\/code><\/h4>\n<p>You can create a promise from a value using <code>Q.fcall<\/code>. This returns a promise for 10.<\/p>\n<pre><code>return Q.fcall(function () {\n    return 10;\n});\n<\/code><\/pre>\n<p>You can also use <code>fcall<\/code> to get a promise for an exception.<\/p>\n<pre><code>return Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\n<\/code><\/pre>\n<p>As the name implies, <code>fcall<\/code> can call functions, or even promised functions. This uses the <code>eventualAdd<\/code> function above to add two numbers.<\/p>\n<pre><code>return Q.fcall(eventualAdd, 2, 2);\n<\/code><\/pre>\n<h4>Using Deferreds<\/h4>\n<p>If you have to interface with asynchronous functions that are callback-based instead of promise-based, Q provides a few shortcuts (like <code>Q.nfcall<\/code> and friends). But much of the time, the solution will be to use <em>deferreds<\/em>.<\/p>\n<pre><code>var 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<\/code><\/pre>\n<p>Note that a deferred can be resolved with a value or a promise. The <code>reject<\/code> function is a shorthand for resolving with a rejected promise.<\/p>\n<pre><code>\/\/ 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<\/code><\/pre>\n<p>This is a simplified implementation of <code>Q.delay<\/code>.<\/p>\n<pre><code>function delay(ms) {\n    var deferred = Q.defer();\n    setTimeout(deferred.resolve, ms);\n    return deferred.promise;\n}\n<\/code><\/pre>\n<p>This is a simplified implementation of <code>Q.timeout<\/code><\/p>\n<pre><code>function 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<\/code><\/pre>\n<p>Finally, you can send a progress notification to the promise with <code>deferred.notify<\/code>.<\/p>\n<p>For illustration, this is a wrapper for XML HTTP requests in the browser. Note that a more thorough implementation would be in order in practice.<\/p>\n<pre><code>function 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<\/code><\/pre>\n<p>Below is an example of how to use this <code>requestOkText<\/code> function:<\/p>\n<pre><code>requestOkText(\"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<\/code><\/pre>\n<h4>Using <code>Q.Promise<\/code><\/h4>\n<p>This is an alternative promise-creation API that has the same power as the deferred concept, but without introducing another conceptual entity.<\/p>\n<p>Rewriting the <code>requestOkText<\/code> example above using <code>Q.Promise<\/code>:<\/p>\n<pre><code>function requestOkText(url) {\n    return Q.Promise(function(resolve, reject, notify) {\n        var request = new XMLHttpRequest();\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                resolve(request.responseText);\n            } else {\n                reject(new Error(\"Status code was \" + request.status));\n            }\n        }\n\n        function onerror() {\n            reject(new Error(\"Can't XHR \" + JSON.stringify(url)));\n        }\n\n        function onprogress(event) {\n            notify(event.loaded \/ event.total);\n        }\n    });\n}\n<\/code><\/pre>\n<p>If <code>requestOkText<\/code> were to throw an exception, the returned promise would be rejected with that thrown exception as the rejection reason.<\/p>\n<h3>The Middle<\/h3>\n<p>If you are using a function that may return a promise, but just might return a value if it doesn\u2019t need to defer, you can use the \u201cstatic\u201d methods of the Q library.<\/p>\n<p>The <code>when<\/code> function is the static equivalent for <code>then<\/code>.<\/p>\n<pre><code>return Q.when(valueOrPromise, function (value) {\n}, function (error) {\n});\n<\/code><\/pre>\n<p>All of the other methods on a promise have static analogs with the same name.<\/p>\n<p>The following are equivalent:<\/p>\n<pre><code>return Q.all([a, b]);\n<\/code><\/pre>\n<pre><code>return Q.fcall(function () {\n    return [a, b];\n})\n.all();\n<\/code><\/pre>\n<p>When working with promises provided by other libraries, you should convert it to a Q promise. Not all promise libraries make the same guarantees as Q and certainly don\u2019t provide all of the same methods. Most libraries only provide a partially functional <code>then<\/code> method. This thankfully is all we need to turn them into vibrant Q promises.<\/p>\n<pre><code>return Q($.ajax(...))\n.then(function () {\n});\n<\/code><\/pre>\n<p>If there is any chance that the promise you receive is not a Q promise as provided by your library, you should wrap it using a Q function. You can even use <code>Q.invoke<\/code> as a shorthand.<\/p>\n<pre><code>return Q.invoke($, 'ajax', ...)\n.then(function () {\n});\n<\/code><\/pre>\n<h3>Over the Wire<\/h3>\n<p>A promise can serve as a proxy for another object, even a remote object. There are methods that allow you to optimistically manipulate properties or call functions. All of these interactions return promises, so they can be chained.<\/p>\n<pre><code>direct 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<\/code><\/pre>\n<p>If the promise is a proxy for a remote object, you can shave round-trips by using these functions instead of <code>then<\/code>. To take advantage of promises for remote objects, check out Q-Connection.<\/p>\n<p>Even in the case of non-remote objects, these methods can be used as shorthand for particularly-simple fulfillment handlers. For example, you can replace<\/p>\n<pre><code>return Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.then(function (value) {\n    return value[0].foo;\n});\n<\/code><\/pre>\n<p>with<\/p>\n<pre><code>return Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.get(0)\n.get(\"foo\");\n<\/code><\/pre>\n<h3>Adapting Node<\/h3>\n<p>If you\u2019re working with functions that make use of the Node.js callback pattern, where callbacks are in the form of <code>function(err, result)<\/code>, Q provides a few useful utility functions for converting between them. The most straightforward are probably <code>Q.nfcall<\/code> and <code>Q.nfapply<\/code> (\u201cNode function call\/apply\u201d) for calling Node.js-style functions and getting back a promise:<\/p>\n<pre><code>return Q.nfcall(FS.readFile, \"foo.txt\", \"utf-8\");\nreturn Q.nfapply(FS.readFile, [\"foo.txt\", \"utf-8\"]);\n<\/code><\/pre>\n<p>If you are working with methods, instead of simple functions, you can easily run in to the usual problems where passing a method to another function\u2014like <code>Q.nfcall<\/code>\u2014\u201cun-binds\u201d the method from its owner. To avoid this, you can either use <code>Function.prototype.bind<\/code> or some nice shortcut methods we provide:<\/p>\n<pre><code>return Q.ninvoke(redisClient, \"get\", \"user:1:id\");\nreturn Q.npost(redisClient, \"get\", [\"user:1:id\"]);\n<\/code><\/pre>\n<p>You can also create reusable wrappers with <code>Q.denodeify<\/code> or <code>Q.nbind<\/code>:<\/p>\n<pre><code>var 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<\/code><\/pre>\n<p>Finally, if you\u2019re working with raw deferred objects, there is a <code>makeNodeResolver<\/code> method on deferreds that can be handy:<\/p>\n<pre><code>var deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", deferred.makeNodeResolver());\nreturn deferred.promise;\n<\/code><\/pre>\n<h3>Long Stack Traces<\/h3>\n<p>Q comes with optional support for \u201clong stack traces,\u201d wherein the <code>stack<\/code> property of <code>Error<\/code> rejection reasons is rewritten to be traced along asynchronous jumps instead of stopping at the most recent one. As an example:<\/p>\n<pre><code>function theDepthsOfMyProgram() {\n  Q.delay(100).done(function explode() {\n    throw new Error(\"boo!\");\n  });\n}\n\ntheDepthsOfMyProgram();\n<\/code><\/pre>\n<p>usually would give a rather unhelpful stack trace looking something like<\/p>\n<pre><code>Error: 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<\/code><\/pre>\n<p>But, if you turn this feature on by setting<\/p>\n<pre><code>Q.longStackSupport = true;\n<\/code><\/pre>\n<p>then the above code gives a nice stack trace to the tune of<\/p>\n<pre><code>Error: 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. (\/path\/to\/test.js:7:1)\n<\/code><\/pre>\n<p>Note how you can see the function that triggered the async operation in the stack trace! This is very helpful for debugging, as otherwise you end up getting only the first line, plus a bunch of Q internals, with no sign of where the operation started.<\/p>\n<p>In node.js, this feature can also be enabled through the Q_DEBUG environment variable:<\/p>\n<pre><code>Q_DEBUG=1 node server.js\n<\/code><\/pre>\n<p>This will enable long stack support in every instance of Q.<\/p>\n<p>This feature does come with somewhat-serious performance and memory overhead, however. If you\u2019re working with lots of promises, or trying to scale a server to many users, you should probably keep it off. But in development, go for it!<\/p>\n<h2>Tests<\/h2>\n<p>You can view the results of the Q test suite in your browser!<\/p>\n<h2>License<\/h2>\n<p>Copyright 2009\u20132015 Kristopher Michael Kowal and contributors MIT License (enclosed)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is Q version 1, from the v1 branch in Git. This documentation applies to the latest of both the version 1 and version 0.9 release trains. These releases are stable. There will be no further releases of 0.9 after 0.9.7 which is nearly equivalent to version 1.0.0. All further releases of q@~1.0 will be [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-8195","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8195","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=8195"}],"version-history":[{"count":2,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8195\/revisions"}],"predecessor-version":[{"id":8730,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8195\/revisions\/8730"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=8195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=8195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=8195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}