Combination of async function + await + setTimeout

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

提交回复
热议问题