Reputation: 843
I have a service worker for my site, but I'm not sure how to get it to handle when there is a network error, I've looked through Mozilla's guides but when I run the worker offline it says that a network error was passed to the respondWith
function, and the catch promise seems to not respond with the cached data.
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/',
'/favicon.ico',
'/f3be2e30f119a1a9b0fdee9fc1f477a9',
'/index.html',
'/sw.js'
]);
})
);
});
this.addEventListener('fetch', function(event) {
var response;
event.respondWith(caches.match(event.request).catch(function() {
return fetch(event.request);
})).then(function(r) {
response = r;
caches.open('v1').then(function(cache) {
cache.put(event.request, response);
});
return response.clone();
}).catch(function(event) {
console.log(event, 'borken');
return caches.match(event.request);
});
});
Upvotes: 4
Views: 2336
Reputation: 10782
You're calling then
on the result of the call to event.respondWith
, which is undefined.
You should chain your then
call after the call to catch
:
var response;
event.respondWith(
caches.match(event.request)
.catch(function() {
return fetch(event.request);
})
.then(function(r) {
response = r;
Not:
var response;
event.respondWith(
caches.match(event.request)
.catch(function() {
return fetch(event.request);
})
)
.then(function(r) {
response = r;
Upvotes: 5