Javascript 获取文档上的事件

Javascript 获取文档上的事件,javascript,events,fetch,Javascript,Events,Fetch,我找不到全局监视文档上的获取事件的方法 在jQuery中,它很简单: var loading = $('#loading'); //my progress bar $(document).bind("ajaxSend", function() { loading.show(); }).bind("ajaxComplete", function() { loading.hide(); }).bind("ajaxSuccess", function() { loading.h

我找不到全局监视文档上的获取事件的方法

在jQuery中,它很简单:

var loading = $('#loading'); //my progress bar
$(document).bind("ajaxSend", function() {
    loading.show();
}).bind("ajaxComplete", function() {
    loading.hide();
}).bind("ajaxSuccess", function() {
    loading.hide();
}).bind("ajaxError", function() {
    loading.hide();
});
但当我开始使用fetchapi时,我就失去了这个功能

为了在获取之前显示加载条并在获取之后隐藏它,我必须侦听哪个事件?另外,我希望在文档上全局执行此操作。我不想这样写:

loading.show();
fetch('...')
   .then(response => response.json())
   .then(answer => { 
        loading.hide()
   }
.....

您可以随时将其取回:

const myFetch = (...args) => {
    loading.show();
    return fetch(...args)
        .then(result => {
            loading.hide();
            return result;
        })
        .catch(error => {
            loading.hide();
            throw error;
        });
};
然后调用
myFetch
,而不是直接调用
fetch

或者,如果您可以假设您的平台(或polyfill)上最终存在

请注意,ES2018规范中将包含完整的信息

如果愿意,您甚至可以包装
fetch
,但我不推荐:

var originalFetch = fetch;
fetch = /*...one of the above, but using `originalFetch` instead of `fetch`...*/

您的代码不使用任何ES2015+功能,因此ES5中的代码块:

function myFetch() {
    loading.show();
    return fetch.apply(null, arguments)
        .then(function(result) {
            loading.hide();
            return result;
        })
        .catch(function(error) {
            loading.hide();
            throw error;
        });
}


谢谢!我得到了它!选择第一个变体。它是有效的,但我也有一个问题,在文档上是否真的没有任何事件可以像jquery那样通过ajax请求监视fetch?@VladimirMedinsky:我在规范中没有看到这样的事件:这就像
XMLHttpRequest
,它也不提供任何全局事件。jQuery的附加功能是附加功能。:-)
function myFetch() {
    loading.show();
    return fetch.apply(null, arguments)
        .then(function(result) {
            loading.hide();
            return result;
        })
        .catch(function(error) {
            loading.hide();
            throw error;
        });
}
function myFetch() {
    loading.show();
    return fetch.apply(null, arguments).finally(function() { loading.hide(); });
}