Skip to content Skip to sidebar Skip to footer

Can One Use The Fetch API As A Request Interceptor?

I'm trying to run some simple JS functions after every request to the server with the Fetch API. I've searched for an answer to this question, but haven't found any, perhaps due to

Solution 1:

Since fetch returns a promise, you can insert yourself in the promise chain by overriding fetch:

(function () {
    var originalFetch = fetch;
    fetch = function() {
        return originalFetch.apply(this, arguments).then(function(data) {
            someFunctionToDoSomething();
            return data;
        });
    };
})();

Example on jsFiddle (since Stack Snippets don't have the handy ajax feature)


Solution 2:

Just like you could overwrite the open method you can also overwrite the global fetch method with an intercepting one:

fetch = (function (origFetch) {
    return function myFetch(req) {
        var result = origFetch.apply(this, arguments);
        result.then(someFunctionToDoSomething);
        return result; // or return the result of the `then` call
    };
})(fetch);

Post a Comment for "Can One Use The Fetch API As A Request Interceptor?"