猿问

有没有人遇到过这个问题哈!JS 异步队列感激不尽

有三个执行函数,如何通过一个异步队列执行函数,使其能按照参数顺序依次输出?
functionf1(){
setTimeout(function(){
console.log('f1')
},300)
}
functionf2(){
setTimeout(function(){
console.log('f2')
},100)
}
functionf3(){
setTimeout(function(){
console.log('f3')
},200)
}
functiondoWork(list){
//TODO
}
doWork([f1,f2,f3])
//期待结果:f1f2f3
凤凰求蛊
浏览 297回答 2
2回答

缥缈止盈

functionf1(){returnnewPromise(function(resolve,reject){setTimeout(function(){resolve('f1');},300);});};//异步函数bfunctionf2(data){returnnewPromise(function(resolve,reject){setTimeout(function(){resolve(data+'f2');},100);});};//异步函数cfunctionf3(data){returnnewPromise(function(resolve,reject){setTimeout(function(){resolve(data+'f3');},200);});};f1().then(function(data){returnf2(data);}).then(function(data){returnf3(data);}).then(function(data){console.log(data);//abc});

鸿蒙传说

functionf(v){returnnewPromise((resolve,reject)=>{setTimeout(function(){resolve(v)},300)})}f1=f('f1')f2=f('f2')f3=f('f3')f1.then((v)=>{console.log(v)returnf2}).then((v)=>{console.log(v)returnf3}).then((v)=>{console.log(v)})依次输出f1f2f3,这是Promise最基本的使用,觉得then麻烦就使用async/await:(async()=>{varpromiseQueue=[f1,f2,f3]for(pofpromiseQueue){letv=awaitpconsole.log(v)}})()
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答