Tag Archives: deferred

How to wait for 2+ asynchronous responses on NodeJS (CommonJS Promises)

Have you ever need to wait for several, unrelated asynchronous functions or processes on NodeJS in order to met dependencies of a last request/method/function/etc? I’m really sure you have, and it can be a pain if you do not know how to properly handle it. The worst and common case is having each one of this nested on then previous one.

There is a really easy and common way I’ve seen lately, that is by using Async.js which is not bad, but it is not that good either, mainly cause it is not a standard. If you want (and you should really want!) a standard way to do such tasks (the right way) then you should start using Promises.

From CommonJS:

Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time. By utilizing a standard interface, different components can return promises for asynchronous actions and consumers can utilize the promises in a predictable manner. Promises can also provide the fundamental entity to be leveraged for more syntactically convenient language-level extensions that assist with asynchronicity.

 

In this example I’ll be demotrating how to use Q (Promises/B proposal by Kris Kowal)  in 3 different use cases: standard functions, NodeJS like functions (callbacks) and finally a simple deferred implementation. Continue reading

Asynchronous loop with jQuery Deferred

On my previous experience with Flex I faced several times the necessity of delegate heavy loops to asynchronous processes; that was because either, the loop was too big or because each item required some heavy data or UI processing.

I was reading today about jQuery’s Deferred object (used mainly on $.when) and I decided to read more about it, understand it and use it when I required it. Deferred is a really simple but powerful object for some situations and one of those turns to be the asynchronous loops.

After some reading, brain overheat, and testing I came with this async loop that receive an options object with 4 properties:

  • total: The number of iterations. By default 0.
  • context: your this context to be sent to the callbacks. By default the loop this object.
  • limit: How many iterations before doing a pause. By default 100.
  • pause: A pause in milliseconds between each chunk. By default 10.

The more useful options are total and context. With those you can create an asynchronous loop that, upon each callback for each iteration will contain the proper this object.

var asyncFor = function(params) {
    var defaults = {
      total: 0,
      limit: 100,
      pause: 10,
      context: this
    },
      options = $.extend(defaults, params),
      def = $.Deferred(),
      step = 0,
      done = 0;

    this.loop = function() {
      if (done < options.total) {
        step = 0;
        for (; step < options.limit; step += 1, done += 1) {
          def.notifyWith(options.context, [done]);
        }
        setTimeout.apply(this, [this.loop, options.pause]);
      } else {
        def.resolveWith(options.context);
      }
    };

    setTimeout.apply(this, [this.loop, options.pause]);
    return def;
  };

 

And a simple example on how to use it:

asyncFor({
  total: 10,
  context: this
}).progress(function(step) {
  console.log(step);
}).done(function() {
  console.log('complete!')
});

 

As a plus, a more complete example demonstrates the big difference while looping 10,000 times synchronously and asynchronously.