您好,欢迎访问一九零五行业门户网

javascript 支持链式调用的异步调用框架Async.Operation_javascript技巧

复制代码 代码如下:
async = {};
async.operation = function(options) {
options = options || {};
var callbackqueue = [];
var chain = (options.chain && options.chain === true) ? true : false;
var started = false;
var innerchain = null;
this.result = undefined;
this.state = running;
this.completed = false;
this.yield = function(result) {
var self = this;
if (!chain) {
self.result = result;
self.state = completed;
self.completed = true;
} else {
started = true;
self.result = result;
self.state = chain running;
self.completed = false;
}
settimeout(function() {
if (!innerchain) {
while (callbackqueue.length > 0) {
var callback = callbackqueue.shift();
if (chain) {
callbackresult = callback(self.result);
self.result = callbackresult;
if (callbackresult && callbackresult instanceof async.operation) {
innerchain = async.chain();
while (callbackqueue.length > 0) {
innerchain.next(callbackqueue.shift());
}
innerchain.next(function(result) {
self.result = result;
self.state = completed;
self.completed = true;
return result;
});
callbackresult.addcallback(function(result) {
self.result = result;
innerchain.go(result);
});
}
} else {
callback(self.result);
}
}
if (!innerchain) {
self.state = completed;
self.completed = true;
}
} else {
while (callbackqueue.length > 0) {
innerchain.next(callbackqueue.shift());
}
innerchain.next(function(result) {
self.result = result;
self.state = completed;
self.completed = true;
return result;
});
}
}, 1);
return this;
};
this.go = function(initialargument) {
return this.yield(initialargument);
}
this.addcallback = function(callback) {
callbackqueue.push(callback);
if (this.completed || (chain && started)) {
this.yield(this.result);
}
return this;
};
this.next = function(nextfunction) {
return this.addcallback(nextfunction);
};
};
async.chain = function(firstfunction) {
var chain = new async.operation({ chain: true });
if (firstfunction) {
chain.next(firstfunction);
}
return chain;
};
async.go = function(initialargument) {
return async.chain().go(initialargument);
}
其它类似信息

推荐信息