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
- Declare an async function:
async function fetchData() { ... }. - Await a promise inside:
const result = await somePromise();. - Wrap awaits in try/catch for error handling.
- Use
awaitwithPromise.all()to run independent tasks concurrently. - Top-level await is supported in ES modules and some REPL environments.
Tips
awaitdoes 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
asyncon the function makesawaita syntax error. - Unhandled rejections in async functions can crash the process if not caught with try/catch or
.catch().