服务工作者错误:事件已经回答了
问题描述:
我不断收到此错误:服务工作者错误:事件已经回答了
Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event has already been responded to.
我知道,如果异步东西的获取函数内的推移该服务人员自动响应,但我不能完全制定出哪些位将是此代码中的罪犯:
importScripts('cache-polyfill.js');
self.addEventListener('fetch', function(event) {
var location = self.location;
console.log("loc", location)
self.clients.matchAll({includeUncontrolled: true}).then(clients => {
for (const client of clients) {
const clientUrl = new URL(client.url);
console.log("SO", clientUrl);
if(clientUrl.searchParams.get("url") != undefined && clientUrl.searchParams.get("url") != '') {
location = client.url;
}
}
console.log("loc2", location)
var url = new URL(location).searchParams.get('url').toString();
console.log(event.request.hostname);
var toRequest = event.request.url;
console.log("Req:", toRequest);
var parser2 = new URL(location);
var parser3 = new URL(url);
var parser = new URL(toRequest);
console.log("if",parser.host,parser2.host,parser.host === parser2.host);
if(parser.host === parser2.host) {
toRequest = toRequest.replace('https://booligoosh.github.io',parser3.protocol + '//' + parser3.host);
console.log("ifdone",toRequest);
}
console.log("toRequest:",toRequest);
event.respondWith(httpGet('https://cors-anywhere.herokuapp.com/' + toRequest));
});
});
function httpGet(theUrl) {
/*var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false); // false for synchronous request
xmlHttp.send(null);
return xmlHttp.responseText;*/
return(fetch(theUrl));
}
任何帮助,将不胜感激。
答
问题是,您致电event.respondWith()
的内容位于您的顶级承诺的.then()
子句内,这意味着它将在顶层承诺解决后异步执行。为了获得您期望的行为,event.respondWith()
需要作为fetch
事件处理程序执行的一部分同步执行。
你的诺言里面的逻辑是有点难以遵循,所以我不完全相信你想实现什么,但一般你可以按照这个模式:
self.addEventListerner('fetch', event => {
// Perform any synchronous checks to see whether you want to respond.
// E.g., check the value of event.request.url.
if (event.request.url.includes('something')) {
const promiseChain = doSomethingAsync()
.then(() => doSomethingAsyncThatReturnsAURL())
.then(someUrl => fetch(someUrl));
// Instead of fetch(), you could have called caches.match(),
// or anything else that returns a promise for a Response.
// Synchronously call event.respondWith(), passing in the
// async promise chain.
event.respondWith(promiseChain);
}
});
这就是大概的概念。 (如果您最终以async
/await
代替承诺,则代码看起来更清晰。)