Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async/await with service worker

I'm fairly new to service workers and almost every tutorial/article I read uses .then() since the service worker relay heavily on promises, but I haven't seen any tutorial using async/await when working with service workers. Is there a reason why? are the tutorials old or I just shouldn't use async/await with service workers?

Example:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

Could have been done using async/await?

Sources I took a look at that use .then()

https://developers.google.com/web/fundamentals/primers/service-workers/registration

https://developers.google.com/web/fundamentals/primers/service-workers

https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle

https://developers.google.com/web/fundamentals/codelabs/offline

like image 684
Patricio Vargas Avatar asked Jan 06 '20 23:01

Patricio Vargas


People also ask

Can I use async await in service worker?

Use async / await in ServiceWorker code because browsers support both. If you want to make a simple page like the one below work without connection, you have an exciting browser feature - Service Worker.

Does async await improve performance?

The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.

Can service workers access local storage?

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

Does service worker work on HTTP?

A service worker intercepts HTTP requests with event listeners (usually the fetch event). This code snippet demonstrates the logic of a Cache-First caching strategy. It's highly recommended to use Workbox to avoid reinventing the wheel. For example, you can register resource URL paths with a single line of regex code.


1 Answers

Promises with then/catch can be used interchangeably with async/await. If you wish, you can replace the then's with awaits and the errors with catches...

// inside an async function
// assuming that register() is a promise-returning function...
try {
  let registration = await navigator.serviceWorker.register('/sw.js')
  console.log('ServiceWorker registration successful with scope: ', registration.scope);
} catch(err) {
  console.log('ServiceWorker registration failed: ', err);
}
like image 112
danh Avatar answered Sep 22 '22 20:09

danh