Combination of async function + await + setTimeout

前端 未结 12 1343
予麋鹿
予麋鹿 2020-11-22 04:34

I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working:

  async function as         


        
相关标签:
12条回答
  • 2020-11-22 05:07

    If you would like to use the same kind of syntax as setTimeout you can write a helper function like this:

    const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
        setTimeout(() => {
            cb();
            resolve();
        }, timeout);
    });
    

    You can then call it like so:

    const doStuffAsync = async () => {
        await setAsyncTimeout(() => {
            // Do stuff
        }, 1000);
    
        await setAsyncTimeout(() => {
            // Do more stuff
        }, 500);
    
        await setAsyncTimeout(() => {
            // Do even more stuff
        }, 2000);
    };
    
    doStuffAsync();
    

    I made a gist: https://gist.github.com/DaveBitter/f44889a2a52ad16b6a5129c39444bb57

    0 讨论(0)
  • 2020-11-22 05:10

    The following code works in Chrome and Firefox and maybe other browsers.

    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    async function sleep(fn, ...args) {
        await timeout(3000);
        return fn(...args);
    }
    

    But in Internet Explorer I get a Syntax Error for the "(resolve **=>** setTimeout..."

    0 讨论(0)
  • 2020-11-22 05:11

    Your sleep function does not work because setTimeout does not (yet?) return a promise that could be awaited. You will need to promisify it manually:

    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    async function sleep(fn, ...args) {
        await timeout(3000);
        return fn(...args);
    }
    

    Btw, to slow down your loop you probably don't want to use a sleep function that takes a callback and defers it like this. I'd rather recommend to do something like

    while (goOn) {
      // other code
      var [parents] = await Promise.all([
          listFiles(nextPageToken).then(requestParents),
          timeout(5000)
      ]);
      // other code
    }
    

    which lets the computation of parents take at least 5 seconds.

    0 讨论(0)
  • 2020-11-22 05:13

    The quick one-liner, inline way

     await new Promise(resolve => setTimeout(resolve, 1000));
    
    0 讨论(0)
  • 2020-11-22 05:14

    Since Node 7.6, you can combine the functions promisify function from the utils module with setTimeout() .

    Node.js

    const sleep = require('util').promisify(setTimeout)
    

    Javascript

    const sleep = m => new Promise(r => setTimeout(r, m))
    

    Usage

    (async () => {
        console.time("Slept for")
        await sleep(3000)
        console.timeEnd("Slept for")
    })()
    
    0 讨论(0)
  • 2020-11-22 05:18
    await setTimeout(()=>{}, 200);
    

    Will work if your Node version is 15 and above.

    0 讨论(0)
提交回复
热议问题