Categories
JavaScript Answers

How to add asynchronous Node.js module exports?

Spread the love

To add asynchronous Node.js module exports, we use promises.

For instance, we write

module.exports = (async () => {
  const db = await require("./db");
  const foo = "bar";

  return {
    foo,
  };
})();

in foo.js to export the promise returned by the async function.

Then we import it by writing

(async () => {
  const foo = await require("./foo");
  console.log(foo);
})();

to call require to require foo.js, which exported the promise returned by the async function.

We use await to get the object returned by the promise.

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 *