[JS] Promise 亮燈

三秒後亮紅燈,二秒後亮綠燈,一秒後亮黃燈,反覆執行。

// 回傳 promise
function lightPromise(second, light) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(light);
    }, second * 1000);
  });
}

function main() {
  const redPromise = lightPromise(3, '[red]'); // 回傳紅燈 promise

  redPromise
    .then((light) => {
      console.log(light, new Date()); // 亮紅燈

      return lightPromise(2, '[green]'); // 回傳綠燈 promise
    })
    .then((light) => {
      console.log(light, new Date()); // 亮綠燈

      return lightPromise(1, '[yellow]'); / 回傳黃燈 promise
    })
    .then((light) => {
      console.log(light, new Date()); // 亮黃燈
      console.log('---------');
      main(); // 再次執行
    });
}

Demo
https://www.yuantw.com/demo/js-promise-light/


參考連結:

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

返回頂端