自从NodeJs出来以后,异步编程便更加系统化和框架话。
var Asy=function(){}
Asy.EmptyFun=function(){}
Asy.Start = function (action, success, failure) {
var asy = new Asy();
asy._addAction(action, success, failure);
return asy;
}
Asy.prototype._addAction=function(action,success,failure){
var _me=this;
_me._actions=_me._actions||[];
_me._actions.push({
action:action||Asy.EmptyFun,
success:success||Asy.EmptyFun,
failure:failure||Asy.EmptyFun
});
}
Asy.prototype.Then=function(action,success,failure){
var _me=this;
_me._addAction(action,success,failure);
return _me;
}
Asy.prototype.Execute=function(){
var _me=this;
var length=_me._actions.length;
var resultFun=function(){
var args = Array.prototype.slice.call(arguments).concat([_me._actions[length - 1].success, _me._actions[length - 1].failure]);
_me._actions[length - 1].action.apply(null, args);
}
for (var i = _me._actions.length - 2; i >= 0 ; i--) {
(function (action) {
var oldResultFun = resultFun;
resultFun = function () {
var newSuccess = function () {
var args = Array.prototype.slice.call(arguments);
action.success.apply(null, args);
oldResultFun.apply(null, args);
};
var args = Array.prototype.slice.call(arguments).concat([newSuccess, action.failure]);
action.action.apply(null, args);
};
})(_me._actions[i]);
};
var args = Array.prototype.slice.call(arguments);
resultFun.apply(null, args);
}
测试:
var testAsyFun = function (i, success, failure) {
console.log("test "+i);
i = i + 1;
success(i);
}
Asy.Start(testAsyFun, function (i) {
console.log("A:" + i);
}).Then(testAsyFun, function (i) {
console.log("B:" + i)
}).Then(testAsyFun, function (i) {
console.log("C:" + i)
}).Execute(1);
结果:
总结:这样玩有点意思,待续中