Categories
JavaScript Answers

How to use async/await at the top level with Node.js?

Spread the love

Sometimes, we want to use async/await at the top level with Node.js.

In this article, we’ll look at how to use async/await at the top level with Node.js.

How to use async/await at the top level with Node.js?

To use async/await at the top level with Node.js, we can create an IIFE.

For instance, we write

(async () => {
  try {
    const text = await main();
    console.log(text);
  } catch (e) {
    // ...
  }
})();

to call the async function immediately after it’s been created by wrapping the function with parentheses and call it with () at the end.

We use await before calling main to return the resolved value of the promise returned by main.

And we use catch to catch any promise rejecttion.

Conclusion

To use async/await at the top level with Node.js, we can create an IIFE.

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 *