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

Viewed 2393

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);
  });
});
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);
}

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

Related