How to use async/await in Node.js

· Category: Node.js

Short answer

async functions return a Promise implicitly, and the await keyword pauses execution within an async function until a Promise resolves, making asynchronous code look synchronous.

Steps

  1. Declare an async function: async function fetchData() { ... }.
  2. Await a promise inside: const result = await somePromise();.
  3. Wrap awaits in try/catch for error handling.
  4. Use await with Promise.all() to run independent tasks concurrently.
  5. Top-level await is supported in ES modules and some REPL environments.

Tips

  • await does not block the main thread; it only pauses the async function while other code can still run.
  • Use Promise.all() instead of sequential awaits when operations do not depend on each other.

Common issues

  • Forgetting async on the function makes await a syntax error.
  • Unhandled rejections in async functions can crash the process if not caught with try/catch or .catch().