【发布时间】: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 后,错误消失了
【问题讨论】: