Combination of async function + await + setTimeout

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

    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);
    }
    

提交回复
热议问题