Service worker error: event already responded to

Service worker error: event already responded to

我不断收到此错误:

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 事件处理程序执行的一部分同步执行。

你的 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);
  }
});

这是大意。 (如果您最终将 promise 替换为 async/await,代码看起来会更清晰。)

我在尝试在获取处理程序中使用 async/await 时也偶然发现了这个错误。正如 Jeff 在他的回答中提到的那样,必须同步调用 event.respondWith 并且参数可以是任何 return 解析为响应的承诺。由于异步函数执行 return 承诺,您所要做的就是将获取逻辑包装在异步函数中,在某些时候,return 是一个响应对象并使用该处理程序调用 event.respondWith .

async function handleRequest(request) {
  const response = await fetch(request)

  // ...perform additional logic

  return response
}

self.addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});