javascript 支持链式调用的异步调用框架Async.Operation


复制代码 代码如下:

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);
}



相关阅读:
Canvas教程(4):Using images应用图像
探秘:Linux在纳斯达克的应用
如何用css改变鼠标显示形状
Linux网络命令介绍:route
域名解析 A记录 MX记录 CNAME记录 TTL
第4课:制作自己的第一个网站
JavaScript 组件之旅(二)编码实现和算法
让textarea控件的滚动条怎是位与最下方
AJAX初体验之实战篇——打造博客无刷新搜索
Js获取电脑屏幕的颜色色彩品质(16位或32位)
如何对PHP程序中的常见漏洞进行攻击(上)
SMTP协议通讯模型
VBS+MSWinsock打造灵巧UDP后门的相关资料
VBS教程:运算符-Xor 运算符
快速导航

Copyright © 2016 phpStudy |