红绿灯题目:实现一个信号灯,这个信号灯,有黄绿红,他们各自亮灯的持续时间是 1s,2s,3s 如此反复。
function delay(fn, time){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(fn());
},time);
});
}
async function light() {
await delay(() => console.log("red"), 3000);
await delay(() => console.log("green"), 2000);
await delay(() => console.log("yellow"), 1000);
await light();
}
light();
light() 是一个带有 async 关键字的函数,代表这是个异步函数。
await 函数接收一个 Promise,并且等待 Promise resolve 之后再继续执行后续代码。
delay() 函数是我们创建的一个返回 Promise 的函数,这个函数在指定时间后异步调用回调函数,注意代码 A 处.