是否存在Service Worker启动waitUntil以延迟处理获取



是否可以让服务工作者等待开始处理获取事件,直到异步工作在服务工作者启动时完成?

我有一个在数据中定义了路由的应用程序外壳。要在服务工作者启动时安装特定的路由获取处理程序,我需要从IndexedDB(异步)中查找路由数据。

不幸的是,在IndexedDB查找完成并设置路由的获取处理之前,服务工作者就开始接受获取事件。

目前,我只是为此硬编码一个特殊情况下的默认处理程序,但最好让服务工作者延迟处理fetch事件,直到在服务工作者启动时IndexedDB处理完成。

我没有找到"等到"的方法,也许我错过了?

代码片段会有所帮助,因为我对这个问题还不是100%清楚。。。但做一些猜测:

直到你解决了提供给event.wait的承诺直到你监听安装事件时,软件不应该拦截任何网络请求,所以在那里设置IDB应该没问题。

一般来说,只运行fetch事件侦听器而不执行任何操作也是可以的,因为在这种情况下,浏览器会像正常情况一样返回到网络。

一般来说,还值得注意的是,SW可以而且确实经常被杀死,这样局部变量就不会在接收不同事件之间徘徊。如果在处理不同的事件时需要一些数据,则应将其保存在IDB或Cacheneneneba API中,然后再次从中获取。

有一个解决方法:

function startupAsyncStuff() {
  return new Promise(function (fulfill, reject) {
    // put here your async stuff and fulfill the promise when done.
  });
}
// Launch your startup async code
var asyncStuffDone = startupAsyncStuff();
// On fetch, wait for the former promise to be resolved first
self.onfetch = function (event) {
  event.respondWith(asyncStuffDone.then(function () {
    // your fetch handling code
  }));
};

由于我使用sw工具箱并在启动时执行异步工作来设置路由处理程序,所以对我来说,最好的解决方案是定义一个临时sw工具箱默认处理程序,直到处理程序准备好响应为止。

var toolbox = require('sw-toolbox');
var setupPromise = someAsyncHandlerSetup()
.then(function () {
  // make default handler temporary, allows other fetch handlers.
  toolbox.router.default = null;
});
// until the async handler setup is done, provide a default handler
// to avoid an offline-dino flash when starting up while offline. 
toolbox.router.default = function defaultHandler (request) {
  return setupPromise.then(function () {
    var handler = toolbox.router.match(request);
    if (handler) {
      return handler(request);
    }
    throw new Error('default handler could not handle ' + request.url);
  });
};

最新更新