长虫山小木屋

没有谁会为你踏雪而来 喜欢的风景要躬亲筚路

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

// 利用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);
});

 

posted on 2019-11-20 15:12  长虫山小木屋  阅读(431)  评论(0编辑  收藏  举报