Node.js Async/Await
Subject: Node.js
What is Async/Await?
- async: Declares an asynchronous function and implicitly returns a Promise.
- await: Pauses the execution inside an async function until a Promise resolves or rejects.
Async/await allows developers to write asynchronous code in a synchronous-looking style, improving readability and maintainability.
Benefits of Async/Await
- Improved Readability
- Simplified Error Handling using
try...catch
- Avoids Callback Nesting
- Synchronous-Like Flow
Example 1: Simulating Asynchronous Operation
Output:
Example 2: Handling File System Asynchronously
Output:
Example 3: Using try...catch for Error Handling
Output:
Example 4: Running Promises in Parallel
Output:
Important Rules of Async/Await
- Await must be inside an async function
- Async functions always return Promises, even when returning simple values
- Await only pauses inside async functions, not globally
- Use try...catch for error handling inside async functions
Practical Use Cases in Node.js
- Reading and writing files using
fs.promises
- Making HTTP requests using
axios
orhttp
- Asynchronous database queries
- Introducing delays with
setTimeout
inside Promises
When Not to Use Await
Avoid using await
inside forEach
. Use:
for...of
loops withawait
for sequencingPromise.all()
for parallel execution
Key Takeaways
- Async/await simplifies handling of asynchronous operations in Node.js
- Improves code readability over callbacks and
.then()
- Error handling is cleaner with
try...catch
- Essential for modern Node.js development workflows