8

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);
  });
});
dkirchhof
  • 185
  • 1
  • 10
  • 2
    Looks like `waitUntil` takes a promise as it's arugment, not a function. Maybe if you invoke your async function immediately, it would work. eg: `event.waitUntil( (async () => { ... })() )` – CRice Nov 15 '17 at 23:33
  • @CRice is correct, your passing a function here not a promise. You could do the IIF way, but I'd say a more obvious easy to understand way would be to create a function called `getClients` that's got all your async stuff, and then do `event.waitUntil(getClients());` – Keith Nov 15 '17 at 23:53
  • @CRice and @Keith Thanks both of you. You're totally right. I mixed some things up... I also tried to use an "external" async function, because i knew that it will return a promise. But actually i just passed its reference instead of calling it (`waitUntil(getClients)` vs `waitUntil(getClients())` – dkirchhof Nov 16 '17 at 00:50

1 Answers1

5

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);
}
dkirchhof
  • 185
  • 1
  • 10
  • Could you tell me what the difference is between your example (in the Q) and this one? Because it looks like you're passing an async function to both.. so what makes one a promise and the other not? Would this work: event.waitUntil( (async () => { /* code */ }()) ); – REJH Dec 13 '17 at 20:39
  • 2
    Actually, i didn't use an iife in my example in the question - in other words: i forgot the parentheses. So it returned just a function, but not a promise. `let a = (async() => { return Promise.resolve() })(); console.log(typeof a, a instanceof Promise); // object true` vs. `let b = async() => { return Promise.resolve() }; console.log(typeof b, b instanceof Promise); // function false` In my answer, i call the the async function which also returns a promise. Before i just passed the function as param to the `event.waitUntil` function (again, just forgot the parentheses). – dkirchhof Dec 14 '17 at 19:39