js之Promise练习 发表于 2019-11-29 红绿黄每隔一秒亮一次;如何让三个灯不断交替重复亮灯?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071function red(){ console.log('red- ', new Date());}function green(){ console.log('green- ', new Date());}function yellow(){ console.log('yellow- ', new Date());}// 地域回调function fn() { setTimeout(() => { red() setTimeout(() => { green() setTimeout(() => { yellow() fn() }, 1000) }, 1000) }, 1000)}fn()// Promise实现function tic(callback, timer) { return new Promise((resolve, reject) => { setTimeout(() => { callback() resolve() }, timer) })}function fn1 () { return tic(red, 1000).then(() => { return tic(green, 1000) }).then(() => { return tic(yellow, 1000) }).then(() => { fn1() })}fn1()// Generator实现function* light(){ yield tic(1000, red); yield tic(2000, green); yield tic(3000, yellow);}function loop(iterator, gen){ var result = iterator.next(); if (result.done) { loop(gen(), gen) } else { result.value.then(function(){ loop(iterator, gen) }) }};loop(light(), light);// async, await实现(async function (){ while(true){ await tic(3000, red); await tic(2000, green); await tic(1000, yellow); }})();