front-end-interview icon indicating copy to clipboard operation
front-end-interview copied to clipboard

Promise的串行调用

Open Liqiuyue9597 opened this issue 4 years ago • 2 comments

let arr = [()=>{ return new Promise(res=>{ console.log("run1", Date.now()); res() }) }, ()=>{ return new Promise(res=>{ console.log("run2", Date.now()); res() }) },()=>{ return new Promise(res=>{ console.log("run3", Date.now()); res() }) }] 写一个函数实现Promise串行调用,按顺序输出run1,run2,run3

function promiseRun(arr) {
       (function iter(){
		if(arr.length) arr.shift()().then(iter)
	})()

}
//另一种
function promiseRun(arr) {
    let res = Promise.resolve();
	arr.forEach(fn=>{
		res = res.then(()=>fn()) // 关键是 res=res.then... 这个逻辑
	})
}
}

Promise提供的方法有.all.race都是并行执行。 一般用async awit就能够串行执行,而且非常简洁明了。

Liqiuyue9597 avatar Aug 18 '20 08:08 Liqiuyue9597

写了一个有关Promise题的总结 一次性解决Promise所有面试题

Liqiuyue9597 avatar Sep 05 '20 07:09 Liqiuyue9597

帮楼主把题目格式化一下

let arr = [
()=>{ 
     return new Promise(res=>{ 
          console.log("run1", Date.now());
          res()
     }) 
}, 
()=>{ 
     return new Promise(res=>{ 
          console.log("run2", Date.now());
          res()
     }) 
}, 
()=>{ 
     return new Promise(res=>{ 
          console.log("run3", Date.now());
          res()
     }) 
}, 
]

liboliang01 avatar Jan 17 '22 08:01 liboliang01