是否有服务工作者启动waitUntil来延迟处理提取?

时间:2015-11-30 23:22:59

标签: asynchronous indexeddb service-worker progressive-web-apps

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

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

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

现在,我只是硬编码一个特殊情况的默认处理程序,但是让服务工作者只是延迟处理获取事件,直到在服务工作者启动时完成IndexedDB处理。

我没有看到“waitUntil”的方法,也许我错过了它?

3 个答案:

答案 0 :(得分:6)

代码片段会有所帮助,因为我不能100%明确这个问题......但是做了一些猜测:

在您收听安装事件时提供给event.waitUntil的承诺之前,SW不应该拦截任何网络请求,因此在那里设置IDB应该没问题。

一般情况下,让fetch事件监听器运行并且不做任何事情也很好,因为在这种情况下浏览器会像往常一样回退到网络。

总的来说,值得注意的是,SWs可以并且确实经常被杀死,因此局部变量不会在接收不同事件之间徘徊。如果处理不同事件时需要一些数据,则应将其保存在IDB或Cache API中,然后再从那里获取。

答案 1 :(得分:3)

有一种解决方法:

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

答案 2 :(得分:0)

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

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