It’s asynchronous, see? So even though all that network code appears before the
returnstatement, it’s pretty much guaranteed to complete after the cache response has been returned. You can verify this by putting in someconsole.logstatements:
Code language: JavaScript
caches.match(request)
.then( responseFromCache => {
if (responseFromCache) {
event.waitUntil(
fetch(request)
.then( responseFromFetch => {
console.log('Got a response from the network.');
caches.open(staticCacheName)
.then( cache => {
cache.put(request, responseFromFetch);
});
})
);
console.log('Got a response from the cache.');
return responseFromCache;
}
Those log statements will appear in this order:
Got a response from the cache. Got a response from the network.That’s the opposite order in which they appear in the code. Everything inside the
event.waitUntilpart is asynchronous.Here’s the catch: this kind of asynchronous
waitUntilhasn’t landed in all the browsers yet. The code I’ve written will fail.But never fear! Jake has written a polyfill. All I need to do is include that at the start of my
serviceworker.jsfile and I’m good to go:
Code language: JavaScript
// Import Jake's polyfill for async waitUntil
importScripts('/js/async-waituntil.js');