Copy codeThe Code is as follows:
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 );
}