Search code examples
javascriptpromiseasync-awaites6-promise

Converting a synchronous function to be async


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.


Solution

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