0

I am curious how you are supposed to set a timeout for a function that returns a callback, if the callback is never fired, the promise will never resolve.

const mockCliAsync = (argv, stdio, timeout) => {
  return new Promise((resolve, reject) => {
    let timedout = false
    const timeoutTimer = setTimeout(() => {
      timedout = true
      kill()
      return reject(new Error('timeout'))
    }, timeout)
    const kill = mockCli(argv, stdio, (error, result) => {
      if (!timedout) {
        clearTimeout(timeoutTimer)
        if (error) return reject(error)
        return resolve(result)
      }
    })
  })
}
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • It looks like there's a similar question, does this help? https://stackoverflow.com/questions/32461271/nodejs-timeout-a-promise-if-failed-to-complete-in-time – kingdaro Mar 20 '18 at 03:10
  • 2
    Use `Promise.race()` as a race between two promises, one backed by a `setTimeout()` and one your actual async operation. – jfriend00 Mar 20 '18 at 03:12
  • There is a lot wrong with that code! `reject()` and `resolve()` are not returned, but called directly. It is possible `kill()` can be called prior to being declared. – Randy Casburn Mar 20 '18 at 03:18

0 Answers0