Tech Is Hard

Credibility = Talent x Years of experience + Proven hardcore accomplishment

Coordinating the Dependent Asynchronous Calls

I think this is better now.  nest() will take an unlimited number of function arguments, coordinating the callback from each to pass the results to the next function.  If there are errors along the way it should callback to the outermost callback.

var nest = function () {
  return _.chain (arguments) .reverse() .reduce (function (next, arg) {
    return function (doc, last) { 
      arg (doc, function (err, doc) {
        if (err)
          last (err);
        else if (next) 
          next (doc, last);
          last (null, doc);
  }, null) .value ();

 * outermost function serving HTTP request
var getFooAPI = function (q, r) {
  nest (getFoo, getSomeOther, sumResults)(q.params, 
    (function (err, doc) {
      if (err)
        r .send ("Error in getFooAPI " + util .inspect (err), 500);
        r .send (doc, 201);

var sumResults = function (doc, handler) {
  handler (null, {"after": "doing some stuff"});

 * Returns a Foo
var getFoo = function getGame(param, handler) {
  return Foo .findById ( .run (handler);

 * Given a Foo document (from the prev find) get me the 
 * other stuff
var getSomeOther = function getGamePicks (Foo, handler) {
  return Other .find ({'':Foo.key}, {stuff: 1}) .run (handler);

As you can see, each function to do something takes an argument that gets passed from its outer call along with a callback function.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: