异步小案例
小于 1 分钟
异步小案例
红绿灯控制任务
红灯 3s 亮一次,绿灯 1s 亮一次,黄灯 2s 亮一次,如果让 3 个灯不断交替地重复亮呢?
function red() {
console.log('red');
}
function green() {
console.log('green')
}
function yellow() {
console.log('yellow')
}
callback 实现
const task = (timer, light, callback) => {
setTimeout(() => {
if (light === 'red') {
red()
} else if (light === 'green') {
green()
} else if (light === 'yellow') {
yellow()
}
// 执行完毕,进行回调
callback()
}, timer)
}
// 回调重复执行
const taskRunner = () => {
task(3000, 'red', () => {
task(2000, 'green', () => {
task(1000, 'yellow', taskRunner)
})
})
}
taskRunner()
Promise 实现
const task = (timer, light) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (light === "red") {
red();
} else if (light === "green") {
green();
} else if (light === "yellow") {
yellow();
}
resolve();
}, timer);
});
};
const taskRunner = () => {
task(3000, "red")
.then(() => task(2000, "green"))
.then(() => task(1000, "yellow"))
.then(taskRunner);
};
taskRunner();
async/await 实现
// Promise 主体部分相同
const taskRunner = async () => {
await task(3000, "red");
await task(2000, "green");
await task(1000, "yellow");
await taskRunner();
};
taskRunner();
Loading...