gpt4 book ai didi

javascript - 服务 worker 错误 : event already responded to

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:11:12 39 4
gpt4 key购买 nike

我一直收到这个错误:

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

我知道如果异步内容在获取函数中发生,服务 worker 会自动响应,但我不能完全弄清楚这段代码中的哪一位是违规者:

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() 的调用是在您的顶级 promise 的 .then() 子句中,这意味着它将在之后异步执行顶级 promise 解决。为了获得您期望的行为,event.respondWith() 需要作为 fetch 事件处理程序执行的一部分同步执行。

你的 promise 中的逻辑有点难以理解,所以我不确定你想要完成什么,但一般来说你可以遵循这种模式:

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 替换 promise,代码看起来会更干净。)

关于javascript - 服务 worker 错误 : event already responded to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46838778/

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