9

用async / await更方便地解决交通灯问题

 3 years ago
source link: https://zhuanlan.zhihu.com/p/141851468
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

用async / await更方便地解决交通灯问题

红灯亮一秒,然后黄灯亮两秒,然后绿灯亮三秒,重复红灯

之前用Promise实现过,见https://github.com/swordrain/traffic-light

现在发现async / await解决该问题更方便,更符合人的思维,寥寥数语而可安邦定国。

function wait(time) {
    return new Promise(resolve=>{
        setTimeout(resolve, time)
    })
}

async function red() {
    console.log('Red:' + new Date())
    await wait(1000)
    yellow()
}

async function yellow() {
    console.log('Yellow:' + new Date())
    await wait(2000)
    green()
}

async function green() {
    console.log('Green:' + new Date())
    await wait(3000)
    red()
}

red()

可见使用async / await后完全就是自然语言逻辑的翻译,毫无异步代码的烦琐。输出结果也木有问题

v2-0ed8dab16fd6a79f6ceab692a441d5f4_720w.jpg


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK