简体   繁体   中英

How do you ensure that the update of a PWA is an "atomic transaction"?

In a PWA I have a JavaScript array installCache with names of files to cache. And this code for updating:

function addInstallListener() {
  self.addEventListener('install',
    event => {
      async function doIinstall() {
        try {
          await event.waitUntil(cache.addAll(installCache));
        } catch (err) {
          console.error("install event", err);
        }
      }
      event.waitUntil(doIinstall());
    }
  );
}
addInstallListener();

This does not work as I expect. I expect all the files listed to be installed on the client, but sometimes not all the files are updated.

The files are uploaded to the server (using firebase deploy ), but the old version of a file may still be in the PWA cache in the browser.

(I am testing this in latest Chrome on Android and Windows 10.)

What is wrong here?

You can get the behavior you describe by ensuring that the promise passed to event.waitUntil() rejects when there's a caching failure. Your current code wraps the async rejection in a catch block but then dosen't re-throw the error, so the overall promise will always end up fulfilling and never reject.

You can do this instead:

self.addEventListener('install', (event) => {
  const doInstall = async () => {
    try {
      const cache = await caches.open('my-cache-name');
      await cache.addAll(installCache);
    } catch (error) {
      // Do whatever logging you want.

      // Important: re-throw the error!
      throw error;
    }
  };

  event.waitUntil(doIinstall());
});

I'd suggest reading through https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#install for an overview of this stage of the service worker lifecycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM