9

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

1 Answer 1

6

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); } 
Sign up to request clarification or add additional context in comments.

2 Comments

So definitely not issues with doing so. I know how to convert the code I just didn't know if I should change it to async/await or not.
@devpato - You can change it, but it would be wrong to say that you should. async/await is just pretty syntax for promises. (edited)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.