我正在尝试下载json文件并缓存它,但出现错误。 这是代码:
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
// With the cache opened, load a JSON file containing an array of files to be cached
return fetch('resource').then(function(response) {
// Once the contents are loaded, convert the raw text to a JavaScript object
return response.json();
}).then(function(files) {
// Use cache.addAll just as you would a hardcoded array of items
console.log('[install] Adding files from JSON file: ', files);
return cache.addAll(files);
});
})
.then(function() {
// Message to simply show the lifecycle flow
console.log(
'[install] All required resources have been cached;',
'the Service Worker was successfully installed!'
);
// Force activation
return self.skipWaiting();
})
);
mysw.js:42未捕获(已承诺)TypeError:无法在“缓存”上执行“ addAll”:迭代器getter不可调用。
cache.addAll(files);似乎有问题。
答案 0 :(得分:0)
然后再尝试:
cache.addAll(files);
使用:
files.map((url) => {
return cache.add(url);
});
因为 cache.addAll(files)将在文件中的1个不可访问时(HTTP 400,401等,有时也是5XX和3XX)失败,以避免全部失败当1失败时,在map循环中使用单独的catch语句。
请查看此答案以获取更多详细信息:https://stackoverflow.com/a/46865785/6375501