// 利用reduce同步处理promise
const p = function(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num)
}, 2000)
})
};
// list: [1, 2, 3, 4,....,'end']
list.reduce(async(pre, cur) => {
const data = await pre;//异步请求
return p(cur)
}, p(0))
衍生一个需要顺序执行,并且全部执行完毕的判断:
let list=["a12", "b13", "c13", "d13", "e13"];
const p = function(num){
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(">>>>>"+num);
resolve("ok"+num);
}, 1000)
})
};
const g = function(){
return new Promise((resolve, reject) => {
list.reduce(async(pre,cur,index)=>{
const data = await pre;//异步
if(index==list.length-1){//最后一个项目
await p(cur);resolve("all loaded")
}
else return p(cur);
},0);
});
}
g().then((e)=>{
console.log(e);
});