Simon
Simon

Reputation: 1693

PWA Service worker match against specific cache timing issue

Fairly new to SW and Promises (and I'm not that good with JS either!) so I might be missing something obvious.

Users have different sections that they can add and delete and the sections contain images they would add to those sections so I want to use SW to cache those images but want to put them in a section numbered cache so if they delete a section I can easily just delete that cache.

Following some research and tutorials I got this working in the 'fetch' event listener:

    var cacheName = `mycache-${id}`;
    event.respondWith(
        caches.match(event.request, { 'ignoreSearch': true }).then(function (resp) {
            return resp || fetch(event.request).then(function (response) {
                return caches.open(cacheName).then(function (cache) {
                    cache.put(event.request, response.clone());
                    return response;
                })
            })
        })
    );

But obviously that's searching all the caches so I assumed it would be more efficient to search the only cache it needs to however this doesn't seem to work, seems like it's hitting the fetch before it can respond with what it might have found in a cache?

    var cacheName = `mycache-${id}`;
    event.respondWith(
        caches.open(cacheName).then(function (cache) {
            console.log("Opened cache");
            cache.match(event.request, { 'ignoreSearch': true }).then(function (resp) {
                console.log("Tried to find a match");
                return resp || fetch(event.request).then(function (response) {
                    return caches.open(cacheName).then(function (cache) {
                        cache.put(event.request, response.clone());
                        return response;
                    })
                })
            })
        })
    );

It is putting the images in the named cache so am I doing something stupid here, I understand that Promises are async but my understanding was the '.then' will wait for a response before it continues.

Upvotes: 0

Views: 232

Answers (1)

Simon
Simon

Reputation: 1693

Ok well it appears it was a simple case of a missing return!

This line:

cache.match(event.request, { 'ignoreSearch': true }).then(function (resp) {

should have been

return cache.match(event.request, { 'ignoreSearch': true }).then(function (resp) {

Upvotes: 1

Related Questions