半年没发掘金了。。。从今天起要开始复习秋招了,好苦555,今年是没有比亚迪拯救的一年,每天写一个题好了,多了我也不会,第一天来个简单的好了,各位5分钟写完噢
这图咋这么大...
循环打印红绿黄——这是一道经典考察异步的场景题,来先写主函数:返回一个promise,在固定时间间隔内打印并改变这个promise的状态即可。
加定时器是由于程序执行太快肉眼看不出他怎么循环的,所以需要来个至少一秒的定时器看看是如何循环打印的,其实不加或者更改定时器毫秒数,打印的顺序是不会变的,大家可以试试
const printLight = (color, delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`${color}`);
resolve(color);
}, delay);
});
};
用then和await语法糖两种形式写都可以
const print = ()=>{
printLight('red',1000)
.then(()=>printLight('green',1000))
.then(()=>printLight('yellow',1000))
.then(print)
}
print()
const print = async () => {
await printLight("red", 1000);
await printLight("green", 1000);
await printLight("yellow", 1000);
await print();
};
print()
是不是很简单! 啊用脑好辛苦!今天可以收工了