【问题标题】:What can cause a Promise rejected with 'InvalidStateError' here?什么会导致 Promise 在此处被 'InvalidStateError' 拒绝?
【发布时间】:2016-12-30 22:16:48
【问题描述】:

什么会导致 Promise 在此处被'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();
    }));
});

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

服务工作者注册!但是 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));
                })
            })
        );
    });
};

这个版本在返回链中传播了一个承诺,使waitUntil() 实际上等待它。它不会缓存,也不会拒绝添加到缓存中失败的单个资源。

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

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

    很可能是 img src 无效,如 here 所述。
    因此,对于cache.addAll,如果其中一个请求无效,则不会保存任何请求。更好地使用:cache.add 如下:

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

    在这种情况下,所有有效的 url 都会被保存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多