Combination of async function + await + setTimeout

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

    Update 2020

    You can await setTimeout with Node.js 15 or above:

    const timersPromises = require('timers/promises');
    
    (async () => {
      const result = await timersPromises.setTimeout(2000, 'resolved')
      // Executed after 2 seconds
      console.log(result); // "resolved"
    })()
    

    Timers Promises API: https://nodejs.org/api/timers.html#timers_timers_promises_api (library already built in Node)


    Note: Stability: 1 - Use of the feature is not recommended in production environments.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 05:20

    Made a util inspired from Dave's answer

    Basically passed in a done callback to call when the operation is finished.

    // Function to timeout if a request is taking too long
    const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
      cb(resolve);
      setTimeout(() => reject('Request is taking too long to response'), timeout);
    });
    

    This is how I use it:

    try {
      await setAsyncTimeout(async done => {
        const requestOne = await someService.post(configs);
        const requestTwo = await someService.get(configs);
        const requestThree = await someService.post(configs);
        done();
      }, 5000); // 5 seconds max for this set of operations
    }
    catch (err) {
      console.error('[Timeout] Unable to complete the operation.', err);
    }
    
    0 讨论(0)
  • 2020-11-22 05:25
    var testAwait = function () {
        var promise = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('Inside test await');
            }, 1000);
        });
        return promise;
    }
    
    var asyncFunction = async function() {
        await testAwait().then((data) => {
            console.log(data);
        })
        return 'hello asyncFunction';
    }
    
    asyncFunction().then((data) => {
        console.log(data);
    });
    
    //Inside test await
    //hello asyncFunction
    
    0 讨论(0)
  • 2020-11-22 05:29

    This is a quicker fix in one-liner.

    Hope this will help.

    // WAIT FOR 200 MILISECONDS TO GET DATA //
    await setTimeout(()=>{}, 200);
    
    0 讨论(0)
  • 2020-11-22 05:30

    This is my version with nodejs now in 2020 in AWS labdas

    const sleep = require('util').promisify(setTimeout)
    
    async function f1 (some){
    ...
    }
    
    async function f2 (thing){
    ...
    }
    
    module.exports.someFunction = async event => {
        ...
        await f1(some)
        await sleep(5000)
        await f2(thing)
        ...
    }
    
    0 讨论(0)
提交回复
热议问题