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);
});
});
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).
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With