-2

As I was implementing service worker subscriptions, I noticed a message from Visual Studio Code, that the following function can be converted to be an async function:

enter image description here

Here is the my original synchronous code.

/**
 * Returns the subscription if it is present, or nothing
 */
function getUserSubscription() {
  return navigator.serviceWorker.ready
    .then(function (serviceWorker) {
      return serviceWorker.pushManager.getSubscription();
    })
    .then(function (pushSubscription) {
      return pushSubscription;
    });
}

I'm not sure how I'd convert this to be an async function. I thought I understood the gist of it, as in converting something like this:

fetchData()
  .then(process())
  .then(processAgain());

to this:

const response1 = await fetchData();
const response2 = await process(response1);
const response = await processAgain(response2);

But I've had no luck converting my function using this technique.

Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
  • Just add the keyword `async` to make `async function getUserSubscription() {...}`. At first glance this may appear to offer no advantage (other than suppressing the pesky warning) but in fact ensures that the function will throw asynchronously. As it stands, if `navigator`, or `navigator.serviceWorker` don't exist then `getUserSubscription()` will throw synchronously but with the `async` keyword, it will return a rejected Promise, thus the caller can expect a Promise to be returned under all cicumstances. – Roamer-1888 Sep 22 '20 at 20:02

1 Answers1

0

Use the async keyword in front of the function. Then await each Promise and return the result.

async function getUserSubscription() {
  const serviceWorker = await navigator.serviceWorker.ready;
  const pushSubscription = await serviceWorker.pushManager.getSubscription();
  return pushSubscription;
}
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32