欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2022-07-09 09:35:25|栏目: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);
}

上一篇:微信小程序自定义状态栏

栏    目:JavaScript代码

下一篇:JavaScript设计模式之代理模式详解

本文标题:javascript 支持链式调用的异步调用框架Async.Operation

本文地址:http://www.codeinn.net/misctech/207242.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有