源代码:
const promiseFuncGenerator = (num) =>
new Array(num).fill(0).map(
(_, index) => () =>
//如果没有用到item可以写成_
new Promise((resolve, reject) => {
setTimeout(() => {
console.log(index);
resolve(index);
}, Math.random() * 1000);
})
);
const proFuncAll = promiseFuncGenerator(10);
const promiseChain = (proFuncAll) => {
proFuncAll.reduce((total, item) => {
return total.then((res) => {
return item();
});
}, Promise.resolve(-1));
};
promiseChain(proFuncAll);
结果图:
知识点:
Promise串行是指每一个由promise封装的任务都顺序执行,即上一个执行完成后再执行下一个。日常开发中会经常用到Promise串行。