Copy Code code 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);
}