我想用javascript编写一个可以运行如下代码的库:
seq.next(function(done){
setTimeout(done,3000);
}).next(function(done){
setTimeout(function(){
console.log("hello");
done();
},4000);
}).end(); //.next morever
实际上我想编写一个可以按顺序(顺序)执行异步功能的库。每个异步函数都应在其末尾运行“done”函数。
有谁可以帮助我。非常感谢!
答案 0 :(得分:2)
图书馆是:
var seq = (function () {
var myarray = [];
var next = function (fn) {
myarray.push({
fn: fn
});
// Return the instance for chaining
return this;
};
var end = function () {
var allFns = myarray;
(function recursive(index) {
var currentItem = allFns[index];
// If end of queue, break
if (!currentItem)
return;
currentItem.fn.call(this, function () {
// Splice off this function from the main Queue
myarray.splice(myarray.indexOf(currentItem), 1);
// Call the next function
recursive(index);
});
}(0));
return this;
}
return {
next: next,
end: end
};
}());
这个库的使用是这样的:
seq.next(function (done) {
setTimeout(done, 4000);
}).next(function (done) {
console.log("hello");
done();
}).next(function (done) {
setTimeout(function () {
console.log('World!');
done();
}, 3000);
}).next(function (done) {
setTimeout(function () {
console.log("OK");
done();
}, 2000);
}).end();