Combination of async function + await + setTimeout

前端 未结 12 1342
予麋鹿
予麋鹿 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

提交回复
热议问题