Re: [whatwg/fetch] Add timeout option (#20)

@ianstormtaylor I think there's some complicated questions about the timeout.

For example, if you specify `timeout: 5000`, should the timeout also include things like `response.json()`? I imagine most of the time the answer is "yes", but then what if you don't call `response.json()`?

In other words, how does `fetch` know that you're "done", so it can cancel the timer?

So I think this is a better design:

```js
async function with_timeout(ms, f) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), ms);

    try {
        return await f(controller.signal);

    } finally {
        clearTimeout(timeoutId);
    }
}
```

Now you can use it like this:

```js
with_timeout(5000, (signal) => fetch(url, { signal }))
```

Or if you want it to also cancel the response:

```js
with_timeout(5000, async (signal) => {
    const response = await fetch(url, { signal });
    return await response.json();
})
```

This is a general solution which isn't tied to `fetch`, so you can also use `with_timeout` in other areas, like Streams.

-- 
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/20#issuecomment-540917173

Received on Friday, 11 October 2019 05:44:36 UTC