async/await 实现 promise 红 绿 蓝灯问题

前言
之前网上有一个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();
小怪兽爱吃肉
浏览 475回答 2
2回答

神不在的星期二

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

两个参数就够啦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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript