Deferreds in loops and recursive functions (Dojo)

When working with deferreds it sometimes is not that easy and intuitive as I thought. If you don’t know perfectly well how the deferreds work, then a little mistake can destroy all the fun you can have with deferreds … and bring you headaches.

Most of the times you probably will use deferreds that are easy to handle, like in the following example:

So in this case you simply create a new deferred object and return its promise to the caller. When the remote call or whatever delays your execution, is finished, the deferred gets resolved and the caller can continue.

The first problem I came across was, when I had to create multiple deferreds inside a loop. I came up with the following solution:

Here we have an external deferred that is used to chain all the deferreds coming from the called function. It’s important to use the result of the “then”-method, which is again a promise! Otherwise the execution wouldn’t be in sequence. There’s a big difference to the former version called “addCallback” where you didn’t need to care about the promises so much.

Finally I had to handle deferreds in a recursive function. A function that calls itself already can create headaches. With deferreds I found the following solution:

This doesn’t look so bad actually. Much better than my versions before, which contained way too many deferred objects. Hope this post clarifies some questions!

This entry was posted in Javascript / HTML / CSS and tagged , , . Bookmark the permalink.

One Response to Deferreds in loops and recursive functions (Dojo)

  1. Chris Beaudette says:

    This is great! Very close to what I need.

    How would you handle a loop within a recursive function? I have to defer the following function until all iterations of the loop within it are complete:

    _parseConfig: function (widgetcfgs) {
    dojoArray.forEach(widgetcfgs, lang.hitch(this, function (widgetcfg, idx) {
    if (widgetcfg.widgets !== null && typeof (widgetcfg.widgets) !== “undefined”) {
    require([widgetcfg.path], lang.hitch(this, function (WidgetPath) {

Leave a Reply

Your email address will not be published. Required fields are marked *

+ three = 5

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">