\href{http://travis-ci.org/kriskowal/q}{\texttt{ }} \href{https://cdnjs.com/libraries/q.js}{\texttt{ }}

\href{http://promises-aplus.github.com/promises-spec}{\texttt{  }}

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 \href{https://github.com/kriskowal/q-connection}{\texttt{ remote object}} to overcome latency.

On the first pass, promises can mitigate the “\href{http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/}{\texttt{ Pyramid of Doom}}”\+: the situation where code marches to the right faster than it marches forward.


\begin{DoxyCode}{0}
\DoxyCodeLine{step1(function (value1) \{}
\DoxyCodeLine{    step2(value1, function(value2) \{}
\DoxyCodeLine{        step3(value2, function(value3) \{}
\DoxyCodeLine{            step4(value3, function(value4) \{}
\DoxyCodeLine{                // Do something with value4}
\DoxyCodeLine{            \});}
\DoxyCodeLine{        \});}
\DoxyCodeLine{    \});}
\DoxyCodeLine{\}); }

\end{DoxyCode}


With a promise library, you can flatten the pyramid.


\begin{DoxyCode}{0}
\DoxyCodeLine{Q.fcall(promisedStep1)}
\DoxyCodeLine{.then(promisedStep2)}
\DoxyCodeLine{.then(promisedStep3)}
\DoxyCodeLine{.then(promisedStep4)}
\DoxyCodeLine{.then(function (value4) \{}
\DoxyCodeLine{    // Do something with value4}
\DoxyCodeLine{\})}
\DoxyCodeLine{.catch(function (error) \{}
\DoxyCodeLine{    // Handle any error from all above steps}
\DoxyCodeLine{\})}
\DoxyCodeLine{.done(); }

\end{DoxyCode}


With this approach, you also get implicit error propagation, just like {\ttfamily try}, {\ttfamily catch}, and {\ttfamily finally}. An error in {\ttfamily promised\+Step1} will flow all the way to the {\ttfamily catch} function, where it’s caught and handled. (Here {\ttfamily promised\+StepN} is a version of {\ttfamily 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 \href{http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript}{\texttt{ 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.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23643}{}\doxysubsection{Getting Started}\label{md_sfcode_node_modules_q_README_autotoc_md23643}
The Q module can be loaded as\+:


\begin{DoxyItemize}
\item A {\ttfamily $<$script$>$} tag (creating a {\ttfamily Q} global variable)\+: $\sim$2.5 KB minified and gzipped.
\item A Node.\+js and Common\+JS module, available in \href{https://npmjs.org/}{\texttt{ npm}} as the \href{https://npmjs.org/package/q}{\texttt{ q}} package
\item An AMD module
\item A \href{https://github.com/component/component}{\texttt{ component}} as {\ttfamily microjs/q}
\item Using \href{http://bower.io/}{\texttt{ bower}} as {\ttfamily q\#$^\wedge$1.4.\+1}
\item Using \href{http://nuget.org/}{\texttt{ Nu\+Get}} as \href{https://nuget.org/packages/q}{\texttt{ Q}}
\end{DoxyItemize}

Q can exchange promises with j\+Query, Dojo, When.\+js, Win\+JS, and more.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23644}{}\doxysubsection{Resources}\label{md_sfcode_node_modules_q_README_autotoc_md23644}
Our \href{https://github.com/kriskowal/q/wiki}{\texttt{ wiki}} contains a number of useful resources, including\+:


\begin{DoxyItemize}
\item A method-\/by-\/method \href{https://github.com/kriskowal/q/wiki/API-Reference}{\texttt{ Q API reference}}.
\item A growing \href{https://github.com/kriskowal/q/wiki/Examples-Gallery}{\texttt{ 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.
\item 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 \href{https://github.com/kriskowal/q/wiki/Libraries}{\texttt{ Libraries}}.
\item If you want materials that introduce the promise concept generally, and the below tutorial isn\textquotesingle{}t doing it for you, check out our collection of \href{https://github.com/kriskowal/q/wiki/General-Promise-Resources}{\texttt{ presentations, blog posts, and podcasts}}.
\item A guide for those \href{https://github.com/kriskowal/q/wiki/Coming-from-jQuery}{\texttt{ coming from j\+Query\textquotesingle{}s {\ttfamily \$.Deferred}}}.
\end{DoxyItemize}

We\textquotesingle{}d also love to have you join the Q-\/\+Continuum \href{https://groups.google.com/forum/\#!forum/q-continuum}{\texttt{ mailing list}}.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23645}{}\doxysubsection{Tutorial}\label{md_sfcode_node_modules_q_README_autotoc_md23645}
Promises have a {\ttfamily then} method, which you can use to get the eventual return value (fulfillment) or thrown exception (rejection).


\begin{DoxyCode}{0}
\DoxyCodeLine{promiseMeSomething()}
\DoxyCodeLine{.then(function (value) \{}
\DoxyCodeLine{\}, function (reason) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


If {\ttfamily promise\+Me\+Something} 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 {\ttfamily promise\+Me\+Something} function 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. {\ttfamily process.\+next\+Tick} in Node). This gives you a nice guarantee when mentally tracing the flow of your code, namely that {\ttfamily then} will always return before either handler is executed.

In this tutorial, we begin with how to consume and work with promises. We\textquotesingle{}ll talk about how to create them, and thus create functions like {\ttfamily promise\+Me\+Something} that return promises, \href{\#the-beginning}{\texttt{ below}}.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23646}{}\doxysubsubsection{Propagation}\label{md_sfcode_node_modules_q_README_autotoc_md23646}
The {\ttfamily then} method returns a promise, which in this example, I’m assigning to {\ttfamily output\+Promise}.


\begin{DoxyCode}{0}
\DoxyCodeLine{var outputPromise = getInputPromise()}
\DoxyCodeLine{.then(function (input) \{}
\DoxyCodeLine{\}, function (reason) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The {\ttfamily output\+Promise} 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 {\ttfamily output\+Promise}.


\begin{DoxyItemize}
\item If you return a value in a handler, {\ttfamily output\+Promise} will get fulfilled.
\item If you throw an exception in a handler, {\ttfamily output\+Promise} will get rejected.
\item If you return a {\bfseries{promise}} in a handler, {\ttfamily output\+Promise} will “become” that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.
\end{DoxyItemize}

If the {\ttfamily get\+Input\+Promise()} promise gets rejected and you omit the rejection handler, the {\bfseries{error}} will go to {\ttfamily output\+Promise}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var outputPromise = getInputPromise()}
\DoxyCodeLine{.then(function (value) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


If the input promise gets fulfilled and you omit the fulfillment handler, the {\bfseries{value}} will go to {\ttfamily output\+Promise}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var outputPromise = getInputPromise()}
\DoxyCodeLine{.then(null, function (error) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


Q promises provide a {\ttfamily fail} shorthand for {\ttfamily then} when you are only interested in handling the error\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var outputPromise = getInputPromise()}
\DoxyCodeLine{.fail(function (error) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


If you are writing Java\+Script for modern engines only or using Coffee\+Script, you may use {\ttfamily catch} instead of {\ttfamily fail}.

Promises also have a {\ttfamily fin} function that is like a {\ttfamily finally} clause. The final handler gets called, with no arguments, when the promise returned by {\ttfamily get\+Input\+Promise()} either returns a value or throws an error. The value returned or error thrown by {\ttfamily get\+Input\+Promise()} passes directly to {\ttfamily output\+Promise} unless the final handler fails, and may be delayed if the final handler returns a promise.


\begin{DoxyCode}{0}
\DoxyCodeLine{var outputPromise = getInputPromise()}
\DoxyCodeLine{.fin(function () \{}
\DoxyCodeLine{    // close files, database connections, stop servers, conclude tests}
\DoxyCodeLine{\}); }

\end{DoxyCode}



\begin{DoxyItemize}
\item If the handler returns a value, the value is ignored
\item If the handler throws an error, the error passes to {\ttfamily output\+Promise}
\item If the handler returns a promise, {\ttfamily output\+Promise} 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.
\end{DoxyItemize}

If you are writing Java\+Script for modern engines only or using Coffee\+Script, you may use {\ttfamily finally} instead of {\ttfamily fin}.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23647}{}\doxysubsubsection{Chaining}\label{md_sfcode_node_modules_q_README_autotoc_md23647}
There are two ways to chain promises. You can chain promises either inside or outside handlers. The next two examples are equivalent.


\begin{DoxyCode}{0}
\DoxyCodeLine{return getUsername()}
\DoxyCodeLine{.then(function (username) \{}
\DoxyCodeLine{    return getUser(username)}
\DoxyCodeLine{    .then(function (user) \{}
\DoxyCodeLine{        // if we get here without an error,}
\DoxyCodeLine{        // the value returned here}
\DoxyCodeLine{        // or the exception thrown here}
\DoxyCodeLine{        // resolves the promise returned}
\DoxyCodeLine{        // by the first line}
\DoxyCodeLine{    \})}
\DoxyCodeLine{\}); }

\end{DoxyCode}



\begin{DoxyCode}{0}
\DoxyCodeLine{return getUsername()}
\DoxyCodeLine{.then(function (username) \{}
\DoxyCodeLine{    return getUser(username);}
\DoxyCodeLine{\})}
\DoxyCodeLine{.then(function (user) \{}
\DoxyCodeLine{    // if we get here without an error,}
\DoxyCodeLine{    // the value returned here}
\DoxyCodeLine{    // or the exception thrown here}
\DoxyCodeLine{    // resolves the promise returned}
\DoxyCodeLine{    // by the first line}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The only difference is nesting. It’s useful to nest handlers if you need to capture multiple input values in your closure.


\begin{DoxyCode}{0}
\DoxyCodeLine{function authenticate() \{}
\DoxyCodeLine{    return getUsername()}
\DoxyCodeLine{    .then(function (username) \{}
\DoxyCodeLine{        return getUser(username);}
\DoxyCodeLine{    \})}
\DoxyCodeLine{    // chained because we will not need the user name in the next event}
\DoxyCodeLine{    .then(function (user) \{}
\DoxyCodeLine{        return getPassword()}
\DoxyCodeLine{        // nested because we need both user and password next}
\DoxyCodeLine{        .then(function (password) \{}
\DoxyCodeLine{            if (user.passwordHash !== hash(password)) \{}
\DoxyCodeLine{                throw new Error("{}Can't authenticate"{});}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \});}
\DoxyCodeLine{    \});}
\DoxyCodeLine{\} }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23648}{}\doxysubsubsection{Combination}\label{md_sfcode_node_modules_q_README_autotoc_md23648}
You can turn an array of promises into a promise for the whole, fulfilled array using {\ttfamily all}.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.all([}
\DoxyCodeLine{    eventualAdd(2, 2),}
\DoxyCodeLine{    eventualAdd(10, 20)}
\DoxyCodeLine{]); }

\end{DoxyCode}


If you have a promise for an array, you can use {\ttfamily spread} as a replacement for {\ttfamily then}. The {\ttfamily 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.


\begin{DoxyCode}{0}
\DoxyCodeLine{function eventualAdd(a, b) \{}
\DoxyCodeLine{    return Q.spread([a, b], function (a, b) \{}
\DoxyCodeLine{        return a + b;}
\DoxyCodeLine{    \})}
\DoxyCodeLine{\} }

\end{DoxyCode}


But {\ttfamily spread} calls {\ttfamily all} initially, so you can skip it in chains.


\begin{DoxyCode}{0}
\DoxyCodeLine{return getUsername()}
\DoxyCodeLine{.then(function (username) \{}
\DoxyCodeLine{    return [username, getUser(username)];}
\DoxyCodeLine{\})}
\DoxyCodeLine{.spread(function (username, user) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The {\ttfamily 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 {\ttfamily all\+Settled}.


\begin{DoxyCode}{0}
\DoxyCodeLine{Q.allSettled(promises)}
\DoxyCodeLine{.then(function (results) \{}
\DoxyCodeLine{    results.forEach(function (result) \{}
\DoxyCodeLine{        if (result.state === "{}fulfilled"{}) \{}
\DoxyCodeLine{            var value = result.value;}
\DoxyCodeLine{        \} else \{}
\DoxyCodeLine{            var reason = result.reason;}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \});}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The {\ttfamily 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.


\begin{DoxyCode}{0}
\DoxyCodeLine{Q.any(promises)}
\DoxyCodeLine{.then(function (first) \{}
\DoxyCodeLine{    // Any of the promises was fulfilled.}
\DoxyCodeLine{\}, function (error) \{}
\DoxyCodeLine{    // All of the promises were rejected.}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23649}{}\doxysubsubsection{Sequences}\label{md_sfcode_node_modules_q_README_autotoc_md23649}
If you have a number of promise-\/producing functions that need to be run sequentially, you can of course do so manually\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return foo(initialVal).then(bar).then(baz).then(qux); }

\end{DoxyCode}


However, if you want to run a dynamically constructed sequence of functions, you\textquotesingle{}ll want something like this\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var funcs = [foo, bar, baz, qux];}
\DoxyCodeLine{}
\DoxyCodeLine{var result = Q(initialVal);}
\DoxyCodeLine{funcs.forEach(function (f) \{}
\DoxyCodeLine{    result = result.then(f);}
\DoxyCodeLine{\});}
\DoxyCodeLine{return result; }

\end{DoxyCode}


You can make this slightly more compact using {\ttfamily reduce}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return funcs.reduce(function (soFar, f) \{}
\DoxyCodeLine{    return soFar.then(f);}
\DoxyCodeLine{\}, Q(initialVal)); }

\end{DoxyCode}


Or, you could use the ultra-\/compact version\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return funcs.reduce(Q.when, Q(initialVal)); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23650}{}\doxysubsubsection{Handling Errors}\label{md_sfcode_node_modules_q_README_autotoc_md23650}
One sometimes-\/unintuitive aspect of promises is that if you throw an exception in the fulfillment handler, it will not be caught by the error handler.


\begin{DoxyCode}{0}
\DoxyCodeLine{return foo()}
\DoxyCodeLine{.then(function (value) \{}
\DoxyCodeLine{    throw new Error("{}Can't bar."{});}
\DoxyCodeLine{\}, function (error) \{}
\DoxyCodeLine{    // We only get here if "{}foo"{} fails}
\DoxyCodeLine{\}); }

\end{DoxyCode}


To see why this is, consider the parallel between promises and {\ttfamily try}/{\ttfamily catch}. We are {\ttfamily try}-\/ing to execute {\ttfamily foo()}\+: the error handler represents a {\ttfamily catch} for {\ttfamily foo()}, while the fulfillment handler represents code that happens {\itshape after} the {\ttfamily try}/{\ttfamily catch} block. That code then needs its own {\ttfamily try}/{\ttfamily catch} block.

In terms of promises, this means chaining your rejection handler\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return foo()}
\DoxyCodeLine{.then(function (value) \{}
\DoxyCodeLine{    throw new Error("{}Can't bar."{});}
\DoxyCodeLine{\})}
\DoxyCodeLine{.fail(function (error) \{}
\DoxyCodeLine{    // We get here with either foo's error or bar's error}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23651}{}\doxysubsubsection{Progress Notification}\label{md_sfcode_node_modules_q_README_autotoc_md23651}
It\textquotesingle{}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 {\ttfamily then}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return uploadFile()}
\DoxyCodeLine{.then(function () \{}
\DoxyCodeLine{    // Success uploading the file}
\DoxyCodeLine{\}, function (err) \{}
\DoxyCodeLine{    // There was an error, and we get the reason for error}
\DoxyCodeLine{\}, function (progress) \{}
\DoxyCodeLine{    // We get notified of the upload's progress as it is executed}
\DoxyCodeLine{\}); }

\end{DoxyCode}


Like {\ttfamily fail}, Q also provides a shorthand for progress callbacks called {\ttfamily progress}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return uploadFile().progress(function (progress) \{}
\DoxyCodeLine{    // We get notified of the upload's progress}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23652}{}\doxysubsubsection{The End}\label{md_sfcode_node_modules_q_README_autotoc_md23652}
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,


\begin{DoxyCode}{0}
\DoxyCodeLine{return foo()}
\DoxyCodeLine{.then(function () \{}
\DoxyCodeLine{    return "{}bar"{};}
\DoxyCodeLine{\}); }

\end{DoxyCode}


Or, end it.


\begin{DoxyCode}{0}
\DoxyCodeLine{foo()}
\DoxyCodeLine{.then(function () \{}
\DoxyCodeLine{    return "{}bar"{};}
\DoxyCodeLine{\})}
\DoxyCodeLine{.done(); }

\end{DoxyCode}


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.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23653}{}\doxysubsubsection{The Beginning}\label{md_sfcode_node_modules_q_README_autotoc_md23653}
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.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23654}{}\doxyparagraph{Using $<$tt$>$\+Q.\+fcall$<$/tt$>$}\label{md_sfcode_node_modules_q_README_autotoc_md23654}
You can create a promise from a value using {\ttfamily Q.\+fcall}. This returns a promise for 10.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.fcall(function () \{}
\DoxyCodeLine{    return 10;}
\DoxyCodeLine{\}); }

\end{DoxyCode}


You can also use {\ttfamily fcall} to get a promise for an exception.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.fcall(function () \{}
\DoxyCodeLine{    throw new Error("{}Can't do it"{});}
\DoxyCodeLine{\}); }

\end{DoxyCode}


As the name implies, {\ttfamily fcall} can call functions, or even promised functions. This uses the {\ttfamily eventual\+Add} function above to add two numbers.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.fcall(eventualAdd, 2, 2); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23655}{}\doxyparagraph{Using Deferreds}\label{md_sfcode_node_modules_q_README_autotoc_md23655}
If you have to interface with asynchronous functions that are callback-\/based instead of promise-\/based, Q provides a few shortcuts (like {\ttfamily Q.\+nfcall} and friends). But much of the time, the solution will be to use {\itshape deferreds}.


\begin{DoxyCode}{0}
\DoxyCodeLine{var deferred = Q.defer();}
\DoxyCodeLine{FS.readFile("{}foo.txt"{}, "{}utf-\/8"{}, function (error, text) \{}
\DoxyCodeLine{    if (error) \{}
\DoxyCodeLine{        deferred.reject(new Error(error));}
\DoxyCodeLine{    \} else \{}
\DoxyCodeLine{        deferred.resolve(text);}
\DoxyCodeLine{    \}}
\DoxyCodeLine{\});}
\DoxyCodeLine{return deferred.promise; }

\end{DoxyCode}


Note that a deferred can be resolved with a value or a promise. The {\ttfamily reject} function is a shorthand for resolving with a rejected promise.


\begin{DoxyCode}{0}
\DoxyCodeLine{// this:}
\DoxyCodeLine{deferred.reject(new Error("{}Can't do it"{}));}
\DoxyCodeLine{}
\DoxyCodeLine{// is shorthand for:}
\DoxyCodeLine{var rejection = Q.fcall(function () \{}
\DoxyCodeLine{    throw new Error("{}Can't do it"{});}
\DoxyCodeLine{\});}
\DoxyCodeLine{deferred.resolve(rejection); }

\end{DoxyCode}


This is a simplified implementation of {\ttfamily Q.\+delay}.


\begin{DoxyCode}{0}
\DoxyCodeLine{function delay(ms) \{}
\DoxyCodeLine{    var deferred = Q.defer();}
\DoxyCodeLine{    setTimeout(deferred.resolve, ms);}
\DoxyCodeLine{    return deferred.promise;}
\DoxyCodeLine{\} }

\end{DoxyCode}


This is a simplified implementation of {\ttfamily Q.\+timeout}


\begin{DoxyCode}{0}
\DoxyCodeLine{function timeout(promise, ms) \{}
\DoxyCodeLine{    var deferred = Q.defer();}
\DoxyCodeLine{    Q.when(promise, deferred.resolve);}
\DoxyCodeLine{    delay(ms).then(function () \{}
\DoxyCodeLine{        deferred.reject(new Error("{}Timed out"{}));}
\DoxyCodeLine{    \});}
\DoxyCodeLine{    return deferred.promise;}
\DoxyCodeLine{\} }

\end{DoxyCode}


Finally, you can send a progress notification to the promise with {\ttfamily deferred.\+notify}.

For illustration, this is a wrapper for XML HTTP requests in the browser. Note that a more \href{https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js\#L29-L73}{\texttt{ thorough}} implementation would be in order in practice.


\begin{DoxyCode}{0}
\DoxyCodeLine{function requestOkText(url) \{}
\DoxyCodeLine{    var request = new XMLHttpRequest();}
\DoxyCodeLine{    var deferred = Q.defer();}
\DoxyCodeLine{}
\DoxyCodeLine{    request.open("{}GET"{}, url, true);}
\DoxyCodeLine{    request.onload = onload;}
\DoxyCodeLine{    request.onerror = onerror;}
\DoxyCodeLine{    request.onprogress = onprogress;}
\DoxyCodeLine{    request.send();}
\DoxyCodeLine{}
\DoxyCodeLine{    function onload() \{}
\DoxyCodeLine{        if (request.status === 200) \{}
\DoxyCodeLine{            deferred.resolve(request.responseText);}
\DoxyCodeLine{        \} else \{}
\DoxyCodeLine{            deferred.reject(new Error("{}Status code was "{} + request.status));}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \}}
\DoxyCodeLine{}
\DoxyCodeLine{    function onerror() \{}
\DoxyCodeLine{        deferred.reject(new Error("{}Can't XHR "{} + JSON.stringify(url)));}
\DoxyCodeLine{    \}}
\DoxyCodeLine{}
\DoxyCodeLine{    function onprogress(event) \{}
\DoxyCodeLine{        deferred.notify(event.loaded / event.total);}
\DoxyCodeLine{    \}}
\DoxyCodeLine{}
\DoxyCodeLine{    return deferred.promise;}
\DoxyCodeLine{\} }

\end{DoxyCode}


Below is an example of how to use this {\ttfamily request\+Ok\+Text} function\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{requestOkText("{}http://localhost:3000"{})}
\DoxyCodeLine{.then(function (responseText) \{}
\DoxyCodeLine{    // If the HTTP response returns 200 OK, log the response text.}
\DoxyCodeLine{    console.log(responseText);}
\DoxyCodeLine{\}, function (error) \{}
\DoxyCodeLine{    // If there's an error or a non-\/200 status code, log the error.}
\DoxyCodeLine{    console.error(error);}
\DoxyCodeLine{\}, function (progress) \{}
\DoxyCodeLine{    // Log the progress as it comes in.}
\DoxyCodeLine{    console.log("{}Request progress: "{} + Math.round(progress * 100) + "{}\%"{});}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23656}{}\doxyparagraph{Using $<$tt$>$\+Q.\+Promise$<$/tt$>$}\label{md_sfcode_node_modules_q_README_autotoc_md23656}
This is an alternative promise-\/creation API that has the same power as the deferred concept, but without introducing another conceptual entity.

Rewriting the {\ttfamily request\+Ok\+Text} example above using {\ttfamily Q.\+Promise}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{function requestOkText(url) \{}
\DoxyCodeLine{    return Q.Promise(function(resolve, reject, notify) \{}
\DoxyCodeLine{        var request = new XMLHttpRequest();}
\DoxyCodeLine{}
\DoxyCodeLine{        request.open("{}GET"{}, url, true);}
\DoxyCodeLine{        request.onload = onload;}
\DoxyCodeLine{        request.onerror = onerror;}
\DoxyCodeLine{        request.onprogress = onprogress;}
\DoxyCodeLine{        request.send();}
\DoxyCodeLine{}
\DoxyCodeLine{        function onload() \{}
\DoxyCodeLine{            if (request.status === 200) \{}
\DoxyCodeLine{                resolve(request.responseText);}
\DoxyCodeLine{            \} else \{}
\DoxyCodeLine{                reject(new Error("{}Status code was "{} + request.status));}
\DoxyCodeLine{            \}}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        function onerror() \{}
\DoxyCodeLine{            reject(new Error("{}Can't XHR "{} + JSON.stringify(url)));}
\DoxyCodeLine{        \}}
\DoxyCodeLine{}
\DoxyCodeLine{        function onprogress(event) \{}
\DoxyCodeLine{            notify(event.loaded / event.total);}
\DoxyCodeLine{        \}}
\DoxyCodeLine{    \});}
\DoxyCodeLine{\} }

\end{DoxyCode}


If {\ttfamily request\+Ok\+Text} were to throw an exception, the returned promise would be rejected with that thrown exception as the rejection reason.\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23657}{}\doxysubsubsection{The Middle}\label{md_sfcode_node_modules_q_README_autotoc_md23657}
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.

The {\ttfamily when} function is the static equivalent for {\ttfamily then}.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.when(valueOrPromise, function (value) \{}
\DoxyCodeLine{\}, function (error) \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


All of the other methods on a promise have static analogs with the same name.

The following are equivalent\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.all([a, b]); }

\end{DoxyCode}



\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.fcall(function () \{}
\DoxyCodeLine{    return [a, b];}
\DoxyCodeLine{\})}
\DoxyCodeLine{.all(); }

\end{DoxyCode}


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 {\ttfamily then} method. This thankfully is all we need to turn them into vibrant Q promises.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q(\$.ajax(...))}
\DoxyCodeLine{.then(function () \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}


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 {\ttfamily Q.\+invoke} as a shorthand.


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.invoke(\$, 'ajax', ...)}
\DoxyCodeLine{.then(function () \{}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23658}{}\doxysubsubsection{Over the Wire}\label{md_sfcode_node_modules_q_README_autotoc_md23658}
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.


\begin{DoxyCode}{0}
\DoxyCodeLine{direct manipulation         using a promise as a proxy}
\DoxyCodeLine{-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/  -\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/-\/}
\DoxyCodeLine{value.foo                   promise.get("{}foo"{})}
\DoxyCodeLine{value.foo = value           promise.put("{}foo"{}, value)}
\DoxyCodeLine{delete value.foo            promise.del("{}foo"{})}
\DoxyCodeLine{value.foo(...args)          promise.post("{}foo"{}, [args])}
\DoxyCodeLine{value.foo(...args)          promise.invoke("{}foo"{}, ...args)}
\DoxyCodeLine{value(...args)              promise.fapply([args])}
\DoxyCodeLine{value(...args)              promise.fcall(...args) }

\end{DoxyCode}


If the promise is a proxy for a remote object, you can shave round-\/trips by using these functions instead of {\ttfamily then}. To take advantage of promises for remote objects, check out \href{https://github.com/kriskowal/q-connection}{\texttt{ 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


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.fcall(function () \{}
\DoxyCodeLine{    return [\{ foo: "{}bar"{} \}, \{ foo: "{}baz"{} \}];}
\DoxyCodeLine{\})}
\DoxyCodeLine{.then(function (value) \{}
\DoxyCodeLine{    return value[0].foo;}
\DoxyCodeLine{\}); }

\end{DoxyCode}


with


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.fcall(function () \{}
\DoxyCodeLine{    return [\{ foo: "{}bar"{} \}, \{ foo: "{}baz"{} \}];}
\DoxyCodeLine{\})}
\DoxyCodeLine{.get(0)}
\DoxyCodeLine{.get("{}foo"{}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23659}{}\doxysubsubsection{Adapting Node}\label{md_sfcode_node_modules_q_README_autotoc_md23659}
If you\textquotesingle{}re working with functions that make use of the Node.\+js callback pattern, where callbacks are in the form of {\ttfamily function(err, result)}, Q provides a few useful utility functions for converting between them. The most straightforward are probably {\ttfamily Q.\+nfcall} and {\ttfamily Q.\+nfapply} (\char`\"{}\+Node function call/apply\char`\"{}) for calling Node.\+js-\/style functions and getting back a promise\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.nfcall(FS.readFile, "{}foo.txt"{}, "{}utf-\/8"{});}
\DoxyCodeLine{return Q.nfapply(FS.readFile, ["{}foo.txt"{}, "{}utf-\/8"{}]); }

\end{DoxyCode}


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 {\ttfamily Q.\+nfcall}—\char`\"{}un-\/binds\char`\"{} the method from its owner. To avoid this, you can either use {\ttfamily Function.\+prototype.\+bind} or some nice shortcut methods we provide\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{return Q.ninvoke(redisClient, "{}get"{}, "{}user:1:id"{});}
\DoxyCodeLine{return Q.npost(redisClient, "{}get"{}, ["{}user:1:id"{}]); }

\end{DoxyCode}


You can also create reusable wrappers with {\ttfamily Q.\+denodeify} or {\ttfamily Q.\+nbind}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var readFile = Q.denodeify(FS.readFile);}
\DoxyCodeLine{return readFile("{}foo.txt"{}, "{}utf-\/8"{});}
\DoxyCodeLine{}
\DoxyCodeLine{var redisClientGet = Q.nbind(redisClient.get, redisClient);}
\DoxyCodeLine{return redisClientGet("{}user:1:id"{}); }

\end{DoxyCode}


Finally, if you\textquotesingle{}re working with raw deferred objects, there is a {\ttfamily make\+Node\+Resolver} method on deferreds that can be handy\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var deferred = Q.defer();}
\DoxyCodeLine{FS.readFile("{}foo.txt"{}, "{}utf-\/8"{}, deferred.makeNodeResolver());}
\DoxyCodeLine{return deferred.promise; }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23660}{}\doxysubsubsection{Long Stack Traces}\label{md_sfcode_node_modules_q_README_autotoc_md23660}
Q comes with optional support for “long stack traces,” wherein the {\ttfamily stack} property of {\ttfamily Error} rejection reasons is rewritten to be traced along asynchronous jumps instead of stopping at the most recent one. As an example\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{function theDepthsOfMyProgram() \{}
\DoxyCodeLine{  Q.delay(100).done(function explode() \{}
\DoxyCodeLine{    throw new Error("{}boo!"{});}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{theDepthsOfMyProgram(); }

\end{DoxyCode}


usually would give a rather unhelpful stack trace looking something like


\begin{DoxyCode}{0}
\DoxyCodeLine{Error: boo!}
\DoxyCodeLine{    at explode (/path/to/test.js:3:11)}
\DoxyCodeLine{    at \_fulfilled (/path/to/test.js:q:54)}
\DoxyCodeLine{    at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)}
\DoxyCodeLine{    at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)}
\DoxyCodeLine{    at pending (/path/to/q.js:397:39)}
\DoxyCodeLine{    at process.startup.processNextTick.process.\_tickCallback (node.js:244:9) }

\end{DoxyCode}


But, if you turn this feature on by setting


\begin{DoxyCode}{0}
\DoxyCodeLine{Q.longStackSupport = true; }

\end{DoxyCode}


then the above code gives a nice stack trace to the tune of


\begin{DoxyCode}{0}
\DoxyCodeLine{Error: boo!}
\DoxyCodeLine{    at explode (/path/to/test.js:3:11)}
\DoxyCodeLine{From previous event:}
\DoxyCodeLine{    at theDepthsOfMyProgram (/path/to/test.js:2:16)}
\DoxyCodeLine{    at Object.<anonymous> (/path/to/test.js:7:1) }

\end{DoxyCode}


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\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{Q\_DEBUG=1 node server.js }

\end{DoxyCode}


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\textquotesingle{}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!\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23661}{}\doxysubsection{Tests}\label{md_sfcode_node_modules_q_README_autotoc_md23661}
You can view the results of the Q test suite \href{https://rawgithub.com/kriskowal/q/v1/spec/q-spec.html}{\texttt{ in your browser}}!\hypertarget{md_sfcode_node_modules_q_README_autotoc_md23662}{}\doxysubsection{License}\label{md_sfcode_node_modules_q_README_autotoc_md23662}
Copyright 2009–2017 Kristopher Michael Kowal and contributors MIT License (enclosed) 