class AsyncSeriesHook {
tasks: Function[];
constructor() {
this.tasks = [];
}
next(task: Function) {
this.tasks.push(task);
return this;
}
callAsync(...args: any) {
const finalCallback = args.pop();
const next = (idx: number, lastResult = null) => {
if (idx === this.tasks.length) {
finalCallback(lastResult, null);
return;
}
const task = this.tasks[idx];
task(...args, lastResult).then(
(res: any) => {
next(idx + 1, res);
},
(err: any) => finalCallback(null, err),
);
};
next(0);
}
run(...args: any) {
return new Promise((resolve, reject) => {
const finalCallback = (res: any, err: any) => {
if (err) {
reject(err);
} else {
resolve(res);
}
};
this.callAsync(...args, finalCallback);
});
}
}
完整的 demo 请看👉 在线效果预览, 查看示例代码请点击此处