有三个执行函数,如何通过一个异步队列执行函数,使其能按照参数顺序依次输出?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
2 回答
缥缈止盈
TA贡献2041条经验 获得超4个赞
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});
鸿蒙传说
TA贡献1865条经验 获得超7个赞
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)}})()
添加回答
举报
0/150
提交
取消