我的服务工作者有一个逻辑,当一个fetch事件发生时,首先它获取一个包含一些布尔值(而不是event.request.url)的端点,并根据我调用事件的值检查值.respondWith()用于当前的fetch事件,我从缓存中提供响应。但是我收到以下错误,
未捕获(在承诺中)DOMException:无法执行' respondWith'上 ' FetchEvent':fetch事件已经响应
我检查here当 m_state 不等于初始
时,会抛出此错误if (m_state != Initial) {
exceptionState.throwDOMException(InvalidStateError, "The fetch event has already been responded to.");
return;
}
我怀疑,因为我有一个额外的获取事件,不知何故它消耗了前一个fetch事件,它正在改变m_state变量,虽然我没有获取事件url。我不知道是什么原因和它的解决方案是什么。但为什么要说
我正在粘贴下面的代码段。
function fetchEvt(event) {
check().then(function (status) {
if (status === 0) {
handleRequest(event);
}
});
}
function checkHash() {
return new Promise(function (resolve) {
fetch(endpoint, { credentials: 'include' }).then(function (response) {
return response.text();
}).then(function (text) {
resolve(text);
});
}
}
function handleRequest(event) {
event.respondWith(caches.match(event.request.url).then(function (Response) {
if (Response) {
return Response;
}
return fetch(event.reuqest);
}));
}
event.respondWith 部分抛出错误。请提示如何解决此问题。
编辑:
function handleRequest(event) {
event.respondWith(checkHash().then(function (status) {
if (status === true) {
caches.match(event.request.url).then(function (Response) {
if (Response) {
return Response;
}
return fetch(event.reuqest);
});
} else if (status === false) return fetch(event.reuqest);
}));
答案 0 :(得分:6)
处理event.respondWith
事件时,您需要同步调用fetch
。如果您不这样做,浏览器会认为它应继续处理请求。这就是为什么当您在代码中调用respondWith
时,请求已经处理,并且您看到 fetch事件已经响应异常。
换句话说:尝试在checkHash
内拨打handleRequest
而不是相反。
答案 1 :(得分:0)
Re“因为我有一个额外的获取事件以某种方式消耗了之前的获取事件”这应该不是问题;您可以在fetch()
事件处理程序中fetch
,事情会很好:
self.addEventListener("fetch", e => {
e.respondWith(
fetch("https://fonts.googleapis.com/css?family=Open+Sans")
.then(_ => fetch(e.request))
);
});
我不太明白你试图用你的代码实现什么,但多次获取,第一次影响第二种行为,工作正常。