Categories
JavaScript Answers

How to wrap async function calls into a sync function in Node.js or JavaScript?

Spread the love

To wrap async function calls into a sync function in Node.js or JavaScript, we create a promise from it.

For instance, we write

const asyncOperation = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("hi");
    }, 3000);
  });
};

const asyncFunction = async () => {
  return await asyncOperation();
};

to create a new promise with the Promise constructor.

We call it with a callback that calls setTime with a callback that calls resolve to settle the promise.

Then we call the asyncOperation function and use await to get the argument we call resolve with.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *