Skip to content

Instantly share code, notes, and snippets.

@thewei
Last active June 11, 2021 02:23
Show Gist options
  • Save thewei/4531273 to your computer and use it in GitHub Desktop.
Save thewei/4531273 to your computer and use it in GitHub Desktop.
Javascript实现异步任务队列类
/*
@Author:thewei
@website:http://www.99is.com
@title: 异步事件任务队列类
*/
(function(){
TaskQe = function(){
this._arrayFn = []; //事件集合
this._callback = {}; //最终回调
this._backdata = []; // 返回数据集合
this._isParallel = false; // 是否并行,默认否
};
// 加入队列
TaskQe.prototype.add = function(fn){
this._arrayFn.push(fn);
return this;
};
// 队列数目
TaskQe.prototype.size = function(){
return this._arrayFn.length;
};
// 获取返回数据集合
TaskQe.prototype.getCallBack = function(){
return this._backdata;
}
// 依次运行队列
TaskQe.prototype.next = function(data){
var fn = this.getNext();
// 并行 or 串行
(this._isParallel)?((fn)&&fn()):((fn)&&((data)?fn(data):fn()));
// 集合返回数据
(data)?this._backdata.push(data):this._backdata.push(false);
// 返回总回调
if(!this.size() && !fn) {
if(typeof this._callback === "function") {
(data)?this._callback(data):this._callback();
}
};
return this;
};
// 队列执行
TaskQe.prototype.getNext = function(){
if(this.size()){
return this._arrayFn.shift();
}
return false;
}
// 初始化,完成后执行,第一个参数是否并行,第二个参数返回
TaskQe.prototype.run = function(){
if(arguments.length === 1 ){
this._callback = (typeof arguments[0] === "function")?arguments[0]:{};
this._isParallel = (typeof arguments[0] === "boolean")?arguments[0]:false;
}
if(arguments.length === 2 ){
this._callback = (typeof arguments[1] === "function")?arguments[1]:{};
this._isParallel = (typeof arguments[0] === "boolean")?arguments[0]:false;
}
var firstFn = this.getNext();
firstFn();
return this;
};
return TaskQe;
})();
// 初始化任务类
var taskQe = new TaskQe();
var aa = function(){
for(var i=1; i<4; i++){
$.ajax({
type:"get",
url: "data/a"+i+".html?_="+new Date().getTime(),
success: function(data){
console.log(i) // 如何把值保存起来
taskQe.next(data); // 通知执行下一个任务
}
});
}
}
// 添加任务
taskQe.add(aa);
// 执行任务
taskQe.run(function(dd){
console.log(dd)
});
/*
// 例子
function a1(lastData){
if(lastData) console.log(lastData);
$.ajax({
type:"get",
url: "data/a1.html?_="+new Date().getTime(),
success: function(data){
taskQe.next(data); // 通知执行下一个任务
}
});
}
function a2(lastData){
if(lastData) console.log(lastData);
$.ajax({
type:"get",
url: "data/a2.html?_="+new Date().getTime(),
success: function(data){
taskQe.next(data); // 通知执行下一个任务
}
});
}
function a3(lastData){
if(lastData) console.log(lastData);
$.ajax({
type:"get",
url: "data/a3.html?_="+new Date().getTime(),
success: function(data){
taskQe.next(data); // 通知执行下一个任务
}
});
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment