javascript 支持链式调用的异步调用框架Async.Operation_javascript技巧
程序员文章站
2022-03-29 13:21:06
...
复制代码 代码如下:
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);
}
推荐阅读
-
JavaScript 异步调用框架 (Part 1 - 问题 & 场景)_javascript技巧
-
JS链式调用的实现方法_javascript技巧
-
JavaScript 异步调用框架 (Part 2 - 用例设计)_javascript技巧
-
JavaScript 异步调用框架 (Part 5 - 链式实现)_javascript技巧
-
JavaScript 异步调用框架 (Part 3 - 代码实现)_javascript技巧
-
JavaScript支持的最大递归调用次数分析_javascript技巧
-
Javscript调用iframe框架页面中函数的方法_javascript技巧
-
js 调用本地exe的例子(支持IE内核的浏览器)_javascript技巧
-
JavaScript 异步调用框架 (Part 6 - 实例 & 模式)_javascript技巧
-
JavaScript 异步调用框架 (Part 4 - 链式调用)_javascript技巧