异步并行
几个异步同时执行,最后一个执行完毕调用一下回调方法
class AsyncParallel{
constructor() {
this.cbList = [];
}
tap(fn) {
this.cbList.push(fn);
}
call(end){
let index = 0;
this.cbList.forEach(fn => {
fn(() => {
index++;
if(index === this.cbList.length){end()};
});
})
}
}
let ap = new AsyncParallel();
ap.tap((cb) => {
setTimeout(() => {
console.log(1);
cb();
}, 3000)
})
ap.tap((cb) => {
setTimeout(() => {
console.log(3);
cb();
}, 1000)
});
ap.call(() => {
console.log('end');
})
异步串行
第一个执行完执行下一个,其实就是用一个next方法去判断执行下一个
class AsyncSerial{
constructor() {
this.cbList = [];
}
tap(fn) {
this.cbList.push(fn);
}
call(end){
let index = 0;
let next = () => {
if(index === this.cbList.length){
end();
return;
}
let fn = this.cbList[index];
fn(() => {
index++;
next();
})
}
next();
}
}
let ap = new AsyncSerial();
ap.tap((cb) => {
setTimeout(() => {
console.log(1);
cb();
}, 3000)
})
ap.tap((cb) => {
setTimeout(() => {
console.log(3);
cb();
}, 2000)
});
ap.call(() => {
console.log('end');
})