Can one use the Fetch API as a Request Interceptor?

后端 未结 2 1939
小蘑菇
小蘑菇 2021-01-18 04:57

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, perh

2条回答
  •  离开以前
    2021-01-18 05:20

    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)

提交回复
热议问题