Async events in ServiceWorkers with "event.waitUntil"
It’s asynchronous, see? So even though all that network code appears before the
return
statement, it’s pretty much guaranteed to complete after the cache response has been returned. You can verify this by putting in someconsole.log
statements:
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.waitUntil
part is asynchronous.Here’s the catch: this kind of asynchronous
waitUntil
hasn’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.js
file and I’m good to go:
Code language: JavaScript
// Import Jake's polyfill for async waitUntil
importScripts('/js/async-waituntil.js');