How to Use Async Await in Node.js: Simple Guide
In Node.js, use
async before a function to make it return a promise, and use await inside that function to pause execution until a promise resolves. This makes asynchronous code easier to read and write like synchronous code.Syntax
The async keyword is placed before a function declaration to mark it as asynchronous. Inside this function, the await keyword pauses the function execution until the awaited promise settles, then returns its result.
- async function: Declares an asynchronous function that returns a promise.
- await expression: Waits for a promise to resolve or reject before continuing.
javascript
async function example() { const result = await someAsyncOperation(); console.log(result); }
Example
This example shows an asynchronous function that waits for a promise to resolve before logging the result. It simulates a delay using setTimeout wrapped in a promise.
javascript
function delay(ms) { return new Promise(resolve => setTimeout(() => resolve('Done waiting!'), ms)); } async function run() { console.log('Start'); const message = await delay(1000); console.log(message); console.log('End'); } run();
Output
Start
Done waiting!
End
Common Pitfalls
Common mistakes include using await outside an async function, which causes syntax errors, and forgetting to handle errors with try/catch. Also, not awaiting promises can lead to unexpected behavior.
javascript
async function wrong() { const data = fetch('https://example.com'); // Missing await console.log(data); // Logs a Promise, not the resolved data } async function right() { try { const response = await fetch('https://example.com'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } }
Quick Reference
Remember these tips when using async/await in Node.js:
- Always use
awaitinside anasyncfunction. - Use
try/catchto handle errors from awaited promises. - Async functions always return a promise.
- Use
awaitto pause execution until a promise resolves.
Key Takeaways
Use
async before functions to enable await inside them.Use
await to pause execution until a promise resolves.Always handle errors in async functions with
try/catch.Do not use
await outside async functions to avoid syntax errors.Async functions return promises, so you can chain them or use
await on them.