Combination of async function + await + setTimeout

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

    setTimeout is not an async function, so you can't use it with ES7 async-await. But you could implement your sleep function using ES6 Promise:

    function sleep (fn, par) {
      return new Promise((resolve) => {
        // wait 3s before calling fn(par)
        setTimeout(() => resolve(fn(par)), 3000)
      })
    }
    

    Then you'll be able to use this new sleep function with ES7 async-await:

    var fileList = await sleep(listFiles, nextPageToken)
    

    Please, note that I'm only answering your question about combining ES7 async/await with setTimeout, though it may not help solve your problem with sending too many requests per second.


    Update: Modern node.js versions has a buid-in async timeout implementation, accessible via util.promisify helper:

    const {promisify} = require('util');
    const setTimeoutAsync = promisify(setTimeout);
    

提交回复
热议问题