前言之前网上有一个promise实现红绿蓝灯交替亮的问题,我再次描述一下问题。题目:红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次;如何让三个灯不断交替重复亮灯?(用Promse实现)functionred(){console.log('red');}functiongreen(){console.log('green');}functionyellow(){console.log('yellow');}然后我最近学习asyncawait的时候来试着实现这个功能。但是我觉得我写的代码不太好,但是又不知道怎么优化,在此贴出希望有人给点建议来优化一下感谢ing!functionred(){console.log('red');}functiongreen(){console.log('green');}functionblue(){console.log('blue');}functionmiddle(cb,time,time1){returnnewPromise((resolve,reject)=>{setTimeout(()=>{cb();resolve(time1);},time);});}asyncfunctionsetp1(){constrTime=awaitmiddle(red,3000,1000);constgTime=awaitmiddle(green,rTime,2000);constbTime=awaitmiddle(blue,gTime);setp1();}setp1();
2 回答
神不在的星期二
TA贡献1963条经验 获得超6个赞
functionred(){console.log('red');}functiongreen(){console.log('green');}functionblue(){console.log('blue');}functionwait(time){returnnewPromise((resolve,reject)=>{setTimeout(resolve,time)})}asyncfunctionmarquee(){awaitwait(3000)red()awaitwait(1000)green()awaitwait(2000)blue()marquee()}marquee()
慕容3067478
TA贡献1773条经验 获得超3个赞
两个参数就够啦functionred(){console.log('red');}functiongreen(){console.log('green');}functionblue(){console.log('blue');}functionmiddle(cb,time){returnnewPromise((resolve,reject)=>{setTimeout(()=>{cb();resolve();},time*1000);});}asyncfunctionsetp1(){constrTime=awaitmiddle(red,3);constgTime=awaitmiddle(green,1);constbTime=awaitmiddle(blue,2);setp1();}setp1();
添加回答
举报
0/150
提交
取消