什么可以导致Promise被'InvalidStateError'拒绝?

Wal*_*ril 1 javascript service-worker

什么可以导致承诺在'InvalidStateError'这里被拒绝?

const SERVICE_WORKER_VERSION = "3.0.0"; // is updated in the build when things change
const CACHE_VERSION = SERVICE_WORKER_VERSION;

const fillServiceWorkerCache = function () {
    /* save in cache some static ressources 
    this happens before activation */
    return caches.open(CACHE_VERSION).then(function(cache) {
        return cache.addAll(ressourcesToSaveInCache);
    });
};

self.addEventListener("install", function (event) {
    /*event.waitUntil takes a promise that should resolves successfully*/
    event.waitUntil(fillServiceWorkerCache().then(function() {
        return self.skipWaiting();
    }));
});
Run Code Online (Sandbox Code Playgroud)

在Firefox版本52上发生以下错误:Service worker event waitUntil() was passed a promise that rejected with 'InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable'.服务工作程序被杀死并在此之后被删除.它适用于Chrome.ressourcesToSaveInCache是一组相对URL.

编辑将其更改为

event.waitUntil(
    fillServiceWorkerCache()
    .then(skipWaiting)
    .catch(skipWaiting)
);
Run Code Online (Sandbox Code Playgroud)

和服务工作者登记!然而fillServiceWorkerCache被拒绝,这是一个大问题(没有脱机缓存).现在问题是为什么fillServiceWorkerCache拒绝,以及试图告诉的错误信息是什么?

编辑灵感来自Hosar的回答:

const fillServiceWorkerCache2 = function () {
    return caches.open(CACHE_VERSION).then(function (cache) {
        return Promise.all(
            ressourcesToSaveInCache.map(function (url) {
                return cache.add(url).catch(function (reason) {
                    return console.log(url + "failed: " + String(reason));
                })
            })
        );
    });
};
Run Code Online (Sandbox Code Playgroud)

这个版本在返回链中传播一个promise,waitUntil()实际上等待它.它不会缓存,也不会拒绝未能在缓存中添加的单个资源.

编辑2:在ressourcesToSaveInCache中修复无效的相对URL后,错误消失了

Hos*_*sar 7

最有可能的是,一个IMG SRC是无效的,提到这里.
因此,cache.addAll如果其中一个请求无效,则不会保存任何请求.更好用:cache.add如下:

return caches.open('cacheName').then(function(cache) {
      Promise.all(
        ressourcesToSaveInCache.map(function(url){cache.add(url)})
      );
    });
Run Code Online (Sandbox Code Playgroud)

在这种情况下,将保存所有有效的URL.