Javascript 异步函数队列
如何创建队列函数。 下面是我需要做的一个例子Javascript 异步函数队列,javascript,asynchronous,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
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
语句
在每个函数中,由于许多原因(单元测试等),这对我来说都是不好的
有没有其他方法可以解决这个问题?我想你可能会感兴趣。其思想是,您立即返回一个对象,该对象将在以后解析。在jQuery中,它通常用于链接AJAX处理程序。