Skip to content Skip to sidebar Skip to footer

Chaining Multiple Asynchronous Methods In Javascript

I am writing a javascript library to abstract ajax requests to my HTTP API. Each of my javascript functions is a wrapper for jquery's ajax call, which makes a callback to the user

Solution 1:

functiondoThingFluent(a, b) {
  return {
    _name : a,
    _chainedCall : b,
    doMoreThingFluent : function(a1) {
      returndoThing(a1, this);
    },
    done : function(callback) {
      var chained = this._chainedCall;
      var name = this._name;
      while (chained) {
        callback = function(n, c) {
          returnfunction() {
            mylib.doThing(n, { success : c });
          };
        } (name, callback);
        name = chained._name;
        chained = chained._chainedCall;
      }

      mylib.doThing(name, {success: callback});
    }
 };

 doThingFluent("foo").doMoreThingFluent("bar").done(function(){alert("done");})

Solution 2:

If you just want to chain unspecified number of successful requests with doing something in the end, listing all things to do as a natural list instead of chain of methods would be even cleaner:

mylib.doThing("foo", "bar", /* all done callback -> */function() { alert("done") })

doThing would have inside a factory that would create either nested callbacks or - even better - iterative manager that'd run all requests in sequence and then call final callback.

Post a Comment for "Chaining Multiple Asynchronous Methods In Javascript"