用普通函數和promise分別實現了兩個版本的Js異步並行與串行。最關鍵的地方在與執行函數的實現,下面貼出代碼來記錄一把。promise
class Executor {
constructor() {
this.tasks = [];
this.tasksPromise = [];
}
register(name, fn) {
this.tasks.push(fn);
}
execute(...args) {
let finalCall =args.pop(),
index=0,
done=()=>{
index++;
if(index==this.tasks.length){
finalCall();
}
};
this.tasks.forEach(fn=>fn(...args,done));
}
registerPromise(name, fn) {
this.tasksPromise.push(fn);
}
executePromise(...args) {
this.tasksPromise = this.tasksPromise.map(fn=>fn(...args));
return Promise.all(this.tasksPromise);
}
}
let excutor = new Executor();
excutor.register('TaskA',function(data,cb){
setTimeout(() => {
console.log(data,'task A....');
cb();
}, 1000);
})
excutor.register('TaskB',function(data,cb){
setTimeout(() => {
console.log(data,'task B....');
cb();
}, 1000);
})
excutor.execute('普通異步並行......',function(){
console.log('普通異步並行 end----');
})
excutor.registerPromise('PromiseA', function (data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(data,'Promise A....');
resolve(data);
}, 3000);
});
})
excutor.registerPromise('PromiseB', function (data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(data,'Promise B....');
resolve(data);
}, 3000);
});
})
excutor.executePromise('Promise異步並行......').then(function() {
console.log('Promise end------');
})
複製代碼
class Executor {
constructor() {
this.tasks = [];
this.tasksPromise = [];
}
register(name, fn) {
this.tasks.push(fn);
}
execute(...args) {
let index = 0;
let finalCallback = args.pop();
let next = (data) => {
if (index == this.tasks.length) return finalCallback(data);
let task = this.tasks[index];
if (index == 0) {
task(...args, next);
} else {
task(data, next);
}
index++;
}
next(...args);
}
registerPromise(name, fn) {
this.tasksPromise.push(fn);
}
executePromise(...args) {
let index = 0;
let p;
let next = (data) => {
p = this.tasksPromise[index++](data);
if (index == this.tasksPromise.length) {
return p;
} else {
return p.then(d => next(d));
}
}
return next(...args)
}
}
let excutor = new Executor();
excutor.register('TaskA',function(data,cb){
setTimeout(() => {
console.log(data);
cb('task A....');
}, 1000);
})
excutor.register('TaskB',function(data,cb){
setTimeout(() => {
console.log(data);
cb('task B....');
}, 1000);
})
excutor.execute('普通異步串行......',function(data){
console.log(data);
console.log('普通異步串行end---');
})
excutor.registerPromise('PromiseA', function (data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(data);
resolve('Promise A....');
}, 3000);
});
})
excutor.registerPromise('PromiseB', function (data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(data);
resolve('Promise B....');
}, 3000);
});
})
excutor.executePromise('Promise異步串行......').then(function (data) {
console.log(data);
console.log('Promise異步串行 end------');
})
複製代碼