Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

service workers: async await in combination with waituntil is not working properly

i'm struggling with promises in a service worker while using async/await syntax.
Following situation: I got a push notification and want to handle the click event. If i use the "old" syntax with then and catch i can iteratore over the list of clients and do something with it. If i use my prefered way with async/await it wouldn't do anything.

self.addEventListener("notificationclick", event => {

  // is working
  event.waitUntil(self.clients.matchAll().then(clientList => {
    console.log(clientList);
  }));

  // is not working
  event.waitUntil(async () => {
    const clientList = await self.clients.matchAll();
    console.log(clientList);
  });
});
like image 571
dkirchhof Avatar asked Nov 15 '17 23:11

dkirchhof


People also ask

What problem does async await solve?

Yes, async/await solves one problem in particular that generators alone cannot—the ability to await some asynchronous value from within a true generator (one yielding actual values, not a coroutine yielding promises or thunks into a trampoline).

Does async await stop execution?

The await expression is usually used to unwrap promises by passing a Promise as the expression . This causes async function execution to pause until the promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.

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.

Why async is used with await?

Use of async and await enables the use of ordinary try / catch blocks around asynchronous code. Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError .


2 Answers

Thanks to @Crice and @Keith,

waitUntil need a promise as argument instead of a function. So this is the working example in async/await style:

self.addEventListener("notificationclick", event =>
{
    event.waitUntil(getClients());
});

async function getClients()
{
    const clientList = await self.clients.matchAll();
    console.log(clientList);
}
like image 110
dkirchhof Avatar answered Oct 01 '22 23:10

dkirchhof


You can modify your original code to make an async IIFE as

  // should be working now
  event.waitUntil( (async () => {
    const clientList = await self.clients.matchAll();
    console.log(clientList);
  })() );

The added ( ), will immediately invokes the async function hence the name async IIFE

like image 44
pref Avatar answered Oct 01 '22 22:10

pref