Hacker Newsnew | comments | show | ask | jobs | submitlogin

This is a rather sensational article. The author's first example is pretty easily solved:

  getFromCache = function (id, callback) {
    asynchronousCache.get(['id', id].join(':'), function(err, myThing) {
      if (myThing == null) {
        asynchronousDB.query("SELECT * from something WHERE id = $id", {id:id}, function(err, myThing) {
          callback(myThing);
        });
      }
      else {
        callback(myThing);
      }
    });
  };

  getFromCache(3222, function (myThing) {
    console.log('myThing:', myThing);
  });



Or if you want more re-usability:

  getFromCache = function (id, query, callback) {
    asynchronousCache.get(['id', id].join(':'), function(err, myThing) {
      if (myThing == null) {
        asynchronousDB.query(query, function(err, myThing) {
          callback(myThing);
        });
      }
      else {
        callback(myThing);
      }
    });
  };

  getFromCacheSomething = function (id, callback) {
    var query = buildQuery("SELECT * from something WHERE id = $id", {id:id});
    getFromCache(id, query, callback);
  }

  getFromCacheSomething(3222, function (myThing) {
    console.log('myThing:', myThing);
  });

-----


Don't forget to bubble errors up the callback chain along with return values (I always forget that too):

    getFromCache = function (id, query, callback) {
      asynchronousCache.get(['id', id].join(':'), function(err, myThing) {
        if (myThing == null) {
          asynchronousDB.query(query, function(err, myThing) {
            callback(err, myThing);
          });
        }
        else {
          callback(err, myThing);
        }
      });
    };

-----


Why the downvotes?

-----




Guidelines | FAQ | Support | API | Lists | Bookmarklet | DMCA | Y Combinator | Apply | Contact

Search: