2016-03-04 1 views
4

У меня есть рабочий для моего сайта, но я не уверен, как его обрабатывать, когда есть сетевая ошибка, я просматривал руководства Mozilla, но когда я запускаю рабочий отключен, он сообщает, что сетевая ошибка была передана функции respondWith, и обещание на уловку, похоже, не отвечает кэшированными данными.Использование служебного работника для улавливания сетевой ошибки

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

Журнал ошибок показан здесь: Error log

ответ

5

Вы звоните then на результат вызова event.respondWith, который является неопределенным.

Вы должны приковать свой then вызов после вызова catch:

var response; 
event.respondWith(
    caches.match(event.request) 
    .catch(function() { 
    return fetch(event.request); 
    }) 
    .then(function(r) { 
    response = r; 

Не:

var response; 
event.respondWith(
    caches.match(event.request) 
    .catch(function() { 
    return fetch(event.request); 
    }) 
) 
.then(function(r) { 
    response = r;