[TypeScript] Simplify asynchronous callback functions using async/await

Learn how to write a promise based delay function and then use it in async await to see how much it simplifies code over setTimeout.

Lets say you want to call a function after 1s, 2s, 3s. You can use setTimeout, or you can wrap it up into a simple delay function that works with async/await

We want to conver this code

const run = (cb) => {
  setTimeout(() => {
    cb('1s');
    setTimeout(() => {
      cb('2s');
      setTimeout(() => {
        cb('3s');
      }, 1000);
    }, 1000);
  }, 1000);
}

to:

const delay = (ms) => new Promise(res => setTimeout(res, ms));

const runAsync = async (cb) => {
  await delay(1000);
  cb('1s');
  await delay(1000);
  cb('2s');
  await delay(1000);
  cb('3s');
}

runAsync((time) => console.log(time));
原文地址:https://www.cnblogs.com/Answer1215/p/6292875.html