异步函数队列

时间:2012-08-02 22:42:57

标签: javascript asynchronous

如何创建函数队列。 这是我需要做的一个例子。

db.connect(); // connecting

db.create({ hello: 'World'}).save(function (success) {
  // Connected ? if so execute this callback immediatly
  // otherwise Queue this whole operation and execute the callback.
});

db.get({ hello: 'World' }, function () {
  // Again connected ? execute immediatly
  // otherwise Queue this whole operation and execute later.
});

我遇到的问题不是关于如何存储和执行回调, 这很容易,问题是如何记录操作?

当然可以这样做

 db.connect(function () {
   // connected ! do stuff..
 })

但它会导致回调地狱!

这是我的实施。

 function Database () {}

 Database.prototype.connect = function () {
   // connect here and emit connected.
   var self = this;
   connect(function () {
     self.connected = true;
     self.executeQueue();
   });
 };

Database.prototype.create = function (doc) {
  var self = this;
  // what should i do here ?

  // maybe ?
  if (self.connected) {
    self._save(doc);
  } else {
    self.addToQueue(function () {
     self._save(doc);
    });
  }
};

上述实现有效,但问题是我必须做的if语句 在每个函数中,这对我来说有很多原因(单元测试等)。

还有其他方法可以解决这个问题吗?

0 个答案:

没有答案
相关问题