HEADS UP! This article was written for an older version of node. More up-to-date information may be available elsewhere.

A Promise is an object that represents the result of an asynchronous function call. Promises are also
called futures and deferreds in some communities.

Goal of this Article

The goal of this article is to introduce CommonJS promises as they exist in NodeJS user-land.
With jQuery popularizing a variant of CommonJS promises for AJAX operations, promises will likely gain
a broader user-base in the browser and on the server.

Brief History of Promises in Node

Promises based on EventEmitters were originally a part of Node. They looked like this:

The style required more allocations than necessary.
There were also political issues because these "promises" did not fulfill all of
the contracts that advocates for promises insisted they must. Between
aesthetics, politics, and reductionism, Ryan removed promises in the v0.2
era and settled on the present callback style, leaving promises as an
exercise for user-land.

Promise Terminology

Fulfillment: When a successful promise is fulfilled, all of the pending callbacks are called with the value. If more callbacks are registered in the future, they will be called with the same value. Fulfilment is the asynchronous analog for returning a value.

Rejection: When a promise cannot be fulfilled, a promise is 'rejected' which invokes the errbacks that are waiting and remembers the error that was rejected for future errbacks that are attached. Rejection is the asynchronous analog for throwing an exception.

Resolution: A promise is resolved when it makes progress toward fulfillment or rejection. A promise can only be resolved once, and it can be resolved with a promise instead of a fulfillment or rejection.

Callback: A function executed if a a promise is fulfilled with a value.

Errback: A function executed if a promise is rejected, with an exception.

Progressback: A function executed to show that progress has been made toward resolution of a promise.

They are compatible and even capable of consuming each others promises, so which you use
is a matter of preference. These libraries do different helper functions outside
of the basic functions necessary to consume and create promises.

The rest of the server-side examples will assume that a q variable referencing
a promise module is in scope.

The Promise Contract

There is one Resolution or Rejection

A promise is resolved one time. It will never be fulfilled if it has been rejected
or rejected if it has been fulfilled.

Listeners are executed one time

An individual callback or errback will be executed once and only once. This follows
from the first rule of the contract.

Promises remember their state

A promise that is resolved with a value remembers the fulfillment. If a
callback is attached in the future to this promise, it will be executed
with the previously resolved value. The same is true of errbacks. If a
promise is rejected and an errback is attached after the rejection, it will
be executed with the rejected value. Promises behave the same way regardless
of whether they are already resolved or resolved in the future.

Thenables

CommonJS promises are sometimes referred to as thenables. This term derives from the then method available on a promise.
The then method is the gateway to attaching callbacks, errbacks, and progressbacks.

myPromise.then(function(){// callback, executed on successful promise resolution},function(){// errback, executed on rejection},function(){// progressback, executed if the promise has progress to report});

When

The when function is a helper to attach listeners to an object that you are
not sure is a promise. This is useful because it is often helpful for methods
to be able to return a promise or a direct value. If a direct value is returned,it will not
have a then method. Also, if the promise does not implement then properly,
the when function makes sure that it behaves properly by ensuring your callbacks
are called in separate events and never more than once.

when(maybePromise,function(){// callback, executed on successful promise resolution or if maybePromise is not a promise but a value},function(){// errback, executed on rejection},function(){// progressback, executed if the promise has progress to report});

Bubbling

The value returned by a callback is bubbled up the chain of promises. The same is true of rejections.
This allows for rejections to be handled at a higher level than the function that called the promise-returning
function that is rejected. This also allows promise-based APIs to compose responses for rejections and successes
by changing the value or error as it is bubbled.

function doSomethingAsync(){return asyncHelper().then(function(val){// do some extra processing on valreturn val;<-- becomes the resolution of the promise returned by doSomethingAsync});}

Creating Promises using the Deferred helper

A Deferred is an object that helps create and manipulate promises. A Deferred
has a promise property that references the promise that it manages. It also
has resolve and reject methods that are responsible for resolving / rejecting
the promise.

resolve is a function that may be passed a value or a promise.
If it is passed a value, the promise is fulfilled.
If it is passed a promise, that promise’s resolution will eventually
be forwarded to this one.

Both Kris Kowal's Q and Kris Zyp's Promised-IO libraries enforce the rule
that a promise can only be resolved once. Kris Kowal’s Q library allows multiple
agents to “race” to be the first to resolve the promise. Kris Zyp’s Promised-IO
throws an exception if you attempt to resolve a promise a second time.

Reject is a function that accepts a reason for rejection. The rejection may be of any type but
is commonly a string. The Deferred rejects its promise with the rejection reason.

Conclusions

Promises are a valuable tool for managing asynchronous control flow. With jQuery adopting
Promises, more JavaScript programmers will see them as the preferred method of managing
asynchronous state. If you have any questions, please leave them in the comments section.

About the Author

About this Article

About HowToNode.org

HowToNode.org is a community supported blog created by Tim Caswell. The purpose of the blog is to teach how to do various tasks in node.js as well as teach fundamental concepts that are needed to write effective code.

This site is powered by Wheat, a git based blogging engine written in node.JS.

The content for this site is stored in a git repository that anyone can fork, write an article, and send a pull request. If your article passes the quality standards it will be published and help support the greater node community.