Re: [whatwg/fetch] Aborting a fetch: The Next Generation (#447)

It is possible to cancel a Fetch request using a Fetch stream reader.

The following example is a quick draft that appears to work well in browsers that support Fetch Streams (the request is aborted after a few bytes of transfer).

```javascript
var fetch = (function() {
    var fetch = window.fetch;
    var cancelableFetch = function() {
        var reader;
        var cancelled = false;
        var request = fetch.apply(this, arguments).then(function(response) {

            reader = response.body.getReader();
            if (cancelled) {
                // abort stream
                reader.cancel();
                return null;
            }

            var body = '';
            var decoder = new TextDecoder();

            function readStream() {
                return reader.read().then(function(result) {
                    if (cancelled) {
                        return null;
                    }
                    body += decoder.decode(result.value || new Uint8Array, {
                        stream: !result.done
                    });
                    if (cancelled) {
                        return null;
                    }
                    if (result.done) {
                        return body;
                    }

                    return readStream();
                })
            }

            return readStream();
        });
        var cancel = function() {
            if (cancelled) {
                return;
            }
            cancelled = true;
            console.warn('Fetch aborted');
            if (!reader) {
                return;
            }
            // abort stream
            reader.cancel();
        };
        return {
            then: function(resolve) { return request.then(resolve); },
            cancel: cancel
        };
    };
    return cancelableFetch;
})();

// reqular fetch request
var request = fetch('https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js');

// regular processing of result
request.then(function(body) {
    console.log("Fetch complete:", (typeof body === 'string') ? body.length : body);
}).catch(function(err) {
    console.log(err.message);
});

// cancel request
request.cancel();
```

Demo: https://jsfiddle.net/4awe08ob/

https://jakearchibald.com/2015/thats-so-fetch/#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/447#issuecomment-313236964

Received on Wednesday, 5 July 2017 21:51:56 UTC