服务工作进程错误:事件已响应

我一直收到此错误:

Unauect(In Promise)DOMException:未能对‘FetchEvent’执行‘RespondWith’:已响应该事件。

我知道,如果FETCH函数中发生异步事件,服务工作者会自动响应,但我不能确定此代码中的哪一位是违规者:

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

您的承诺中的逻辑有点难以遵循,所以我不太确定您想要实现什么,但总的来说,您可以遵循以下模式:

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,则代码看起来更加整洁。)

相关文章