zoukankan      html  css  js  c++  java
  • [Typescript] Promise based delay function 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

    const delay = (ms) => new Promise(res => setTimeout(res, ms));
    
    const runAsync = async (cb) => { 
      await delay(100);
      cb('1s')
      await delay(1000);
      cb('2s')
      await delay(1000);
      cb('3s')
    } 
    
    runAsync((m) => { console.log(m)})

    or normal promise:

    const delay = ms => new Promise(res => setTimeout(res, ms));
    
    const runAsync = cb => {
      Promise.resolve()
        .then(() => {
          cb("1s");
          return delay(1000);
        })
        .then(() => {
          cb("2s");
          return delay(1000);
        })
        .then(() => {
          cb("3s");
          return delay(1000);
        });
    };
    
    runAsync(m => {
      console.log(m);
    });
  • 相关阅读:
    My Tornado Particle Effect
    [zz] 海洋环境的光能传递
    一道算法题
    Alembic
    一些莫名其妙的东东
    Python Q&A
    <<Exceptional C++>> notes
    CG Rendering v.s. Browser Rendering
    Modo
    Katana
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8343347.html
Copyright © 2011-2022 走看看