run_the_race
run_the_race

Reputation: 2398

JavaScript how to use event.waitUntil() to wait for an async function call

When learning about JavaScript it recommends using async/await as it's much more readable than .then, and I agree. Unfortunately when it comes to PWA service workers, async seems to be forgotten.

When trying to create an install function for a service worker with async style:

const cacheVersion = "v1";
const cacheAssets = [
    "/",
    "/index.html",
    "/static/img/logo.svg",
];

async function install(version, assets) {
    const cache = await caches.open(version);
    console.log("Doing stuff....");
}

self.addEventListener("install", (event) => {
    console.log("Service Worker INSTALL START");
    event.waitUntil(install, cacheVersion, cacheAssets); // <--- Does not call install()
    console.log("Service Worker INSTALL COMPLETE");
});

The install function is never run. If I change this line:

event.waitUntil(install, cacheVersion, cacheAssets);

to

install(cacheVersion, cacheAssets);

Then the line is run, but not waited for, causing problems.

How does one use event.waitUntil to call an async function and wait for it?

To me event.waitUntil is like await, so why have this weird special function that blocks the main loop, when it seems like nothing else in JS does? Just seems so strange to me.

Upvotes: 7

Views: 2610

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074545

install isn't called because you don't call it. waitUntil accepts a promise, not a function. An async function isn't a promise, it's a function that returns a promise.

Call your function and pass the promise it returns into waitUntil:

event.waitUntil(install(cacheVersion, cacheAssets));
// −−−−−−−−−−−−−−−−−−−−^−−−−−−−−−−−−−−−−−−−−−−−−−^

Upvotes: 8

Related Questions