Re: [whatwg/fetch] Add option to reject the fetch promise automatically after a certain time elapsed (with no API for arbitrary aborts) (#179)

I use this, based on @buraktamturk's suggestion.

```js
const networkTimeoutError = new Error('Network request timeout')

function getTimeout({ timeout }) {
  if (timeout && timeout.constructor === Promise) {
    return timeout
  }
  if (typeof timeout === 'number') {
    return new Promise(resolve => {
      setTimeout(resolve, timeout)
    })
  }
}

export default function fetchWithTimeout(url, config) {
  return new Promise((resolve, reject) => {
    let completed = false
    const timeout = getTimeout(config)
    const wrap = (thing, ...pre) => (...args) => {
      if (!completed) {
        completed = true
        return thing(...pre, ...args)
      }
    }
    delete config.timeout
    if (timeout) {
      timeout.then(wrap(reject, networkTimeoutError))
    }
    return fetch(url, config)
      .then(wrap(resolve))
      .catch(wrap(reject))
  })
}
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/179#issuecomment-457698748

Received on Friday, 25 January 2019 19:37:54 UTC