最近遇到個面試題:點亮綠燈3s,而後點亮黃燈1s,而後點亮紅燈2s,而後重複循環。估計是考察ES6 Promise相關內容。那如何更好的實現呢?javascript
function red () { console.log('red') } function green () { console.log('green') } function yellow() { console.log('yellow') } function genPromise(func, timeout) { return () => { func(); return new Promise((resolve) => setTimeout(resolve, timeout)) } } var redPromise = genPromise(red, 2000), greenPromise = genPromise(green, 3000), yellowPromise = genPromise(yellow, 1000); function step() { greenPromise().then(() => yellowPromise()).then(() => redPromise()).then(() => step()) } // 啓動 step();
step函數的貌似寫複雜了,yellowPromise函數自己返回的就是個Promise對象,那給then方法傳遞的箭頭函數冗餘了。修改step函數:java
function step() { greenPromise().then(yellowPromise).then(redPromise).then(step) } //啓動 step();
使用async/wait改進下step函數:面試
async function step() { await greenPromise(); await yellowPromise(); await redPromise(); step(); } // 啓動 step();