gpt4 book ai didi

javascript - Serviceworker Bug event.respondWith

转载 作者:数据小太阳 更新时间:2023-10-29 05:18:16 25 4
gpt4 key购买 nike

我的 serviceworker 有这样的逻辑,当一个获取事件发生时,首先它获取一个包含一些 bool 值(不是 event.request.url)的端点并根据我调用的值检查该值 事件.respondWith() 对于当前的获取事件,我在其中提供来自缓存的响应。但是我收到以下错误,

Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The fetch event has already been responded to

我检查了herem_state 不等于 Initial

时抛出此错误
if (m_state != Initial) {
exceptionState.throwDOMException(InvalidStateError, "The fetch event has already been responded to.");
return;
}

我怀疑,因为我有一个额外的获取事件,它以某种方式消耗了以前的获取事件,它正在更改 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);
}));

最佳答案

处理fetch事件时需要同步调用event.respondWith。如果您不这样做,浏览器会假定它应该继续处理请求。这就是为什么当您开始在代码中调用 respondWith 时,请求已得到处理并且您会看到 fetch 事件已被响应 异常。

换句话说:尝试在 handleRequest 中调用您的 checkHash,而不是相反。

关于javascript - Serviceworker Bug event.respondWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36062941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com