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

(编辑:jimmy 日期: 2024/10/10 浏览:2)

复制代码 代码如下:
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);
}
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。