vendredi 1 septembre 2017

ServiceWorkers: Return cached response and fetch response

I'm wanting to cache volatile data with my service worker. My thought is to return first with the possibly stale cache match, and simultaneously fire off the fetch request and return that data if/when the fetch is successful.

This is the code I'm running for non-volatile data that I want to cache:

return e.respondWith(
    caches.match(request.url).then(function(cacheResponse) {
        // Found it in the cache
        if (cacheResponse) {
            console.log('[ServiceWorker] Found it in Cache')
            return cacheResponse
        // Not in the cache
        } else {
            console.log('[ServiceWorker] Not in Cache')
            return fetch(request).then(function(fetchResponse) {
                console.log('[ServiceWorker] Fetched from API', fetchResponse)
                // don't cache errors
                if (!(fetchResponse && fetchResponse.status === 200)) {
                    console.log('[ServiceWorker] Fetch error, no cache')
                    return fetchResponse
                }
                return caches.open(cacheName).then(function(cache) {
                    cache.put(request.url, fetchResponse.clone())
                    console.log('[ServiceWorker] Fetched and Cached Data', request.url)
                    return fetchResponse
                })
            })
        }
    })
)

How would I return both the cachedResponse and the fetchResponse asynchronously? Is this possible?

Thanks for the help!

Aucun commentaire:

Enregistrer un commentaire