How to implement a “function timeout” in Javascript - not just the 'setTimeout'

后端 未结 5 1369
情歌与酒
情歌与酒 2020-12-16 00:33

How to implement a timeout in Javascript, not the window.timeout but something like session timeout or socket timeout - basically - a

5条回答
  •  独厮守ぢ
    2020-12-16 00:56

    I realize this is an old question/thread but perhaps this will be helpful to others.

    Here's a generic callWithTimeout that you can await:

    export function callWithTimeout(func, timeout) {
      return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timeout")), timeout)
        func().then(
          response => resolve(response),
          err => reject(new Error(err))
        ).finally(() => clearTimeout(timer))
      })
    }
    

    Tests/examples:

    export function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms))
    }
    
    const func1 = async () => {
      // test: func completes in time
      await sleep(100)
    }
    
    const func2 = async () => {
      // test: func does not complete in time
      await sleep(300)
    }
    
    const func3 = async () => {
      // test: func throws exception before timeout
      await sleep(100)
      throw new Error("exception in func")
    }
    
    const func4 = async () => {
      // test: func would have thrown exception but timeout occurred first
      await sleep(300)
      throw new Error("exception in func")
    }
    

    Call with:

    try {
      await callWithTimeout(func, 200)
      console.log("finished in time")
    }
    catch (err) {
      console.log(err.message)  // can be "timeout" or exception thrown by `func`
    }
    

提交回复
热议问题