It seems that my dojo/request article got a few views, so I figured I would take a moment to talk about dojo/promise, another major enhancement in the core of the Dojo Toolkit in 1.8.  Mark Wubben rewrote the promise API while keeping it compatible with the “modern” Dojo promise API.

Just a reminder, the “modern” promise API arrived in Dojo 1.5, where “callback chaining” and the promise was introduced.  Prior to that you had to use addCallback and addErrback when dealing with a Deferred object.  As of 1.5, the API changed so you could do something like this:

None of that changes for 1.8, but the underpinnings have totally changed and there is a more robust API for managing promises and futures.  In 1.8, the new abstract class of dojo/promise/Promise is introduced.  This provides the core API of Promises in Dojo and is what dojo/Deferred now implements.  Plus there are a couple of new syntactically named methods:

Dealing with multiple promises (like for example, making several requests to several services) and then doing something when one or all of them were resolved was dealt with dojo/DeferredList.  While that is still there (and still works), dojo/promise has introduced two new syntactically named modules dojo/promise/all and dojo/promise/first, which will roll up a bunch of promises and return you a new promise that could work something like this:

The last significant “new thing” in my opinion is that there is the dojo/promise/tracer.  What this does is essentially allow you to centrally manage the events of Promises.  What you do is load the module and then on any of your Promises/Deferred, turn on trace by calling the .trace() (or .traceRejected()):

So like dojo/promise, I think there are some really “cool” things coming in 1.8 in the “core” of Dojo.

4 thoughts on “dojo/promise

  1. Nice writeup!

    The original Deferred implementation is still there, as dojo/_base/Deferred and dojo.Deferred. The deferreds created by that class have a .promise that is an instance of dojo/promise/Promise though. You have to include the new implementation separately.

    both() is actually always(), and fail() will soon change to otherwise().

    Also, cancel() can be passed a reason, which is forwarded to the canceler. This allows for communication into the promise chain as to why it needs to be canceled.

  2. I love dojo, must so because its readability! Congratulations the work!!!
    Just a question: The original deferred syntax will be removed in dojo 2.0?

    1. Yes. Everything that has been deprecated will be dropped in 2.0. We need to update this about deferreds, but this will give you an idea of the sorts of things that you can do to make sure your code is as ready for 2.0 as possible: Dojo 2.0 Migration Guide

Comments are closed.