A library for promises (CommonJS/Promises/A,B,D)
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 backward
compatible. The version 2 release train introduces significant and
backward-incompatible changes and is experimental at this time.
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.
On the first pass, promises can mitigate the “Pyramid of Doom”: the situation where code marches to the right faster than it marches forward.
step1step2value1step3value2step4value3// Do something with value4;;;;
With a promise library, you can flatten the pyramid.
QfcallpromisedStep1thenpromisedStep2thenpromisedStep3thenpromisedStep4then// Do something with value4catch// Handle any error from all above stepsdone;
With this approach, you also get implicit error propagation, just like
finally. An error in
promisedStep1 will flow all the way to
catch function, where it’s caught and handled. (Here
a version of
stepN that returns a promise.)
The callback approach is called an “inversion of control”. A function that accepts a callback instead of a return value is saying, “Don’t call me, I’ll call you.”. Promises un-invert the inversion, cleanly separating the input arguments from control flow arguments. This simplifies the use and creation of API’s, particularly variadic, rest and spread arguments.
The Q module can be loaded as:
<script>tag (creating a
Qglobal variable): ~2.5 KB minified and gzipped.
Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more.
Our wiki contains a number of useful resources, including:
We'd also love to have you join the Q-Continuum mailing list.
Promises have a
then method, which you can use to get the eventual
return value (fulfillment) or thrown exception (rejection).
promiseMeSomething 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
gets rejected later by a thrown exception, the second function (the
rejection handler) will be called with the exception.
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.
process.nextTick in Node). This gives you a nice
guarantee when mentally tracing the flow of your code, namely that
then will always return before either handler is executed.
In this tutorial, we begin with how to consume and work with promises. We'll
talk about how to create them, and thus create functions like
promiseMeSomething that return promises, below.
then method returns a promise, which in this example, I’m
var outputPromise = getInputPromisethen;
outputPromise 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
If you return a value in a handler,
outputPromise will get
If you throw an exception in a handler,
outputPromise will get
If you return a promise in a handler,
“become” that promise. Being able to become a new promise is useful
for managing delays, combining results, or recovering from errors.
getInputPromise() promise gets rejected and you omit the
rejection handler, the error will go to
var outputPromise = getInputPromisethen;
If the input promise gets fulfilled and you omit the fulfillment handler, the
value will go to
var outputPromise = getInputPromisethennull;
Q promises provide a
fail shorthand for
then when you are only
interested in handling the error:
var outputPromise = getInputPromisefail;
CoffeeScript, you may use
catch instead of
Promises also have a
fin function that is like a
The final handler gets called, with no arguments, when the promise
getInputPromise() either returns a value or throws an
error. The value returned or error thrown by
passes directly to
outputPromise unless the final handler fails, and
may be delayed if the final handler returns a promise.
var outputPromise = getInputPromisefin// close files, database connections, stop servers, conclude tests;
outputPromisegets 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.
CoffeeScript, you may use
finally instead of
There are two ways to chain promises. You can chain promises either inside or outside handlers. The next two examples are equivalent.
return getUsernamethenreturn getUserusernamethen// if we get here without an error,// the value returned here// or the exception thrown here// resolves the promise returned// by the first line;
return getUsernamethenreturn getUserusername;then// if we get here without an error,// the value returned here// or the exception thrown here// resolves the promise returned// by the first line;
The only difference is nesting. It’s useful to nest handlers if you need to capture multiple input values in your closure.
return getUsernamethenreturn getUserusername;// chained because we will not need the user name in the next eventthenreturn getPassword// nested because we need both user and password nextthenif userpasswordHash !== hashpasswordthrow "Can't authenticate";;;
You can turn an array of promises into a promise for the whole,
fulfilled array using
return QalleventualAdd2 2eventualAdd10 20;
If you have a promise for an array, you can use
spread as a
spread function “spreads” 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.
return Qspreada breturn a + b;
all initially, so you can skip it in chains.
return getUsernamethenreturn username getUserusername;spread;
all 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
QallSettledpromisesthenresultsforEachif resultstate === "fulfilled"var value = resultvalue;elsevar reason = resultreason;;;
any 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.
Qanypromisesthen// Any of the promises was fulfilled.// All of the promises were rejected.;
If you have a number of promise-producing functions that need to be run sequentially, you can of course do so manually:
However, if you want to run a dynamically constructed sequence of functions, you'll want something like this:
var funcs = foo bar baz qux;var result = QinitialVal;funcsforEachresult = resultthenf;;return result;
You can make this slightly more compact using
return funcsreducereturn soFarthenf;QinitialVal;
Or, you could use the ultra-compact version:
return funcsreduceQwhen QinitialVal;
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.
return foothenthrow "Can't bar.";// We only get here if "foo" fails;
To see why this is, consider the parallel between promises and
catch. We are
try-ing to execute
foo(): the error
handler represents a
foo(), while the fulfillment handler
represents code that happens after the
That code then needs its own
In terms of promises, this means chaining your rejection handler:
return foothenthrow "Can't bar.";fail// We get here with either foo's error or bar's error;
It's 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
return uploadFilethen// Success uploading the file// There was an error, and we get the reason for error// We get notified of the upload's progress as it is executed;
fail, Q also provides a shorthand for progress callbacks
return uploadFileprogress// We get notified of the upload's progress;
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’s an unfortunate pattern that the exceptions can go unobserved.
So, either return it,
return foothenreturn "bar";;
Or, end it.
Ending a promise chain makes sure that, if an error doesn’t get handled before the end, it will get rethrown and reported.
This is a stopgap. We are exploring ways to make unhandled errors visible without any explicit handling.
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.
You can create a promise from a value using
Q.fcall. This returns a
promise for 10.
return Qfcallreturn 10;;
You can also use
fcall to get a promise for an exception.
return Qfcallthrow "Can't do it";;
As the name implies,
fcall can call functions, or even promised
functions. This uses the
eventualAdd function above to add two
return QfcalleventualAdd 2 2;
If you have to interface with asynchronous functions that are callback-based
instead of promise-based, Q provides a few shortcuts (like
friends). But much of the time, the solution will be to use deferreds.
var deferred = Qdefer;FSreadFile"foo.txt" "utf-8"if errordeferredrejecterror;elsedeferredresolvetext;;return deferredpromise;
Note that a deferred can be resolved with a value or a promise. The
reject function is a shorthand for resolving with a rejected
// this:deferredreject"Can't do it";// is shorthand for:var rejection = Qfcallthrow "Can't do it";;deferredresolverejection;
This is a simplified implementation of
var deferred = Qdefer;setTimeoutdeferredresolve ms;return deferredpromise;
This is a simplified implementation of
var deferred = Qdefer;Qwhenpromise deferredresolve;delaymsthendeferredreject"Timed out";;return deferredpromise;
Finally, you can send a progress notification to the promise with
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.
var request = ;var deferred = Qdefer;requestopen"GET" url true;requestonload = onload;requestonerror = onerror;requestonprogress = onprogress;requestsend;if requeststatus === 200deferredresolverequestresponseText;elsedeferredreject"Status code was " + requeststatus;deferredreject"Can't XHR " + JSONstringifyurl;deferrednotifyeventloaded / eventtotal;return deferredpromise;
Below is an example of how to use this
requestOkText""then// If the HTTP response returns 200 OK, log the response text.console.logresponseText;// If there's an error or a non-200 status code, log the error.console.errorerror;// Log the progress as it comes in.console.log"Request progress: " + Mathroundprogress * 100 + "%";;
This is an alternative promise-creation API that has the same power as the deferred concept, but without introducing another conceptual entity.
requestOkText example above using
return QPromisevar request = ;requestopen"GET" url true;requestonload = onload;requestonerror = onerror;requestonprogress = onprogress;requestsend;if requeststatus === 200resolverequestresponseText;elsereject"Status code was " + requeststatus;reject"Can't XHR " + JSONstringifyurl;notifyeventloaded / eventtotal;;
requestOkText were to throw an exception, the returned promise would be
rejected with that thrown exception as the rejection reason.
If you are using a function that may return a promise, but just might return a value if it doesn’t need to defer, you can use the “static” methods of the Q library.
when function is the static equivalent for
All of the other methods on a promise have static analogs with the same name.
The following are equivalent:
return Qalla b;
return Qfcallreturn a b;all;
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’t provide all of the same methods.
Most libraries only provide a partially functional
This thankfully is all we need to turn them into vibrant Q promises.
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
Q.invoke as a shorthand.
return Qinvoke$ 'ajax'then;
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.
direct manipulation using a promise as a proxy-------------------------- -------------------------------value.foo promise.get("foo")value.foo = value promise.put("foo", value)delete value.foo promise.del("foo")value.foo(...args) promise.post("foo", [args])value.foo(...args) promise.invoke("foo", ...args)value(...args) promise.fapply([args])value(...args) promise.fcall(...args)
If the promise is a proxy for a remote object, you can shave
round-trips by using these functions instead of
then. To take
advantage of promises for remote objects, check out Q-Connection.
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
return Qfcallreturn foo: "bar" foo: "baz" ;thenreturn value0foo;;
return Qfcallreturn foo: "bar" foo: "baz" ;get0get"foo";
If you're working with functions that make use of the Node.js callback pattern,
where callbacks are in the form of
function(err, result), Q provides a few
useful utility functions for converting between them. The most straightforward
Q.nfapply ("Node function call/apply") for calling
Node.js-style functions and getting back a promise:
return QnfcallFSreadFile "foo.txt" "utf-8";return QnfapplyFSreadFile "foo.txt" "utf-8";
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—like
Q.nfcall—"un-binds" the method from its owner. To avoid this, you can either
Function.prototype.bind or some nice shortcut methods we provide:
return QninvokeredisClient "get" "user:1:id";return QnpostredisClient "get" "user:1:id";
You can also create reusable wrappers with
var readFile = QdenodeifyFSreadFile;return readFile"foo.txt" "utf-8";var redisClientGet = QnbindredisClientget redisClient;return redisClientGet"user:1:id";
Finally, if you're working with raw deferred objects, there is a
makeNodeResolver method on deferreds that can be handy:
var deferred = Qdefer;FSreadFile"foo.txt" "utf-8" deferredmakeNodeResolver;return deferredpromise;
Q comes with optional support for “long stack traces,” wherein the
Error rejection reasons is rewritten to be traced along
asynchronous jumps instead of stopping at the most recent one. As an example:
usually would give a rather unhelpful stack trace looking something like
Error: boo!at explode (/path/to/test.js:3:11)at _fulfilled (/path/to/test.js:q:54)at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)at pending (/path/to/q.js:397:39)at process.startup.processNextTick.process._tickCallback (node.js:244:9)
But, if you turn this feature on by setting
QlongStackSupport = true;
then the above code gives a nice stack trace to the tune of
Error: boo!at explode (/path/to/test.js:3:11)From previous event:at theDepthsOfMyProgram (/path/to/test.js:2:16)at Object.<anonymous> (/path/to/test.js:7:1)
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.
In node.js, this feature can also be enabled through the Q_DEBUG environment variable:
Q_DEBUG=1 node server.js
This will enable long stack support in every instance of Q.
This feature does come with somewhat-serious performance and memory overhead, however. If you're 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!
You can view the results of the Q test suite in your browser!
Copyright 2009–2015 Kristopher Michael Kowal and contributors MIT License (enclosed)