front-end-interview
front-end-interview copied to clipboard
Promise的串行调用
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
就能够串行执行,而且非常简洁明了。
写了一个有关Promise题的总结 一次性解决Promise所有面试题
帮楼主把题目格式化一下
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()
})
},
]