Async/await helps you write code that waits for tasks to finish without blocking everything else. It makes working with things that take time, like loading data, easier to read and understand.
0
0
Async/await syntax in Node.js
Introduction
When you need to get data from the internet before continuing.
When reading or writing files and you want to wait for the operation to finish.
When calling a function that takes time and you want to handle the result after it completes.
When you want to avoid confusing chains of callbacks and make your code cleaner.
When you want to handle errors easily in asynchronous code.
Syntax
Node.js
async function functionName() { const result = await someAsyncTask(); console.log(result); }
The async keyword before a function means it returns a promise and can use await.
The await keyword pauses the function until the promise resolves, then returns the value.
Examples
This example waits for a promise that immediately resolves with 'Hello!' and then prints it.
Node.js
async function greet() { const message = await Promise.resolve('Hello!'); console.log(message); }
This example waits for 1 second before printing a message.
Node.js
async function waitAndPrint() { await new Promise(resolve => setTimeout(resolve, 1000)); console.log('Waited 1 second'); }
This example shows how to fetch data from the internet and handle errors using async/await.
Node.js
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } }
Sample Program
This program fetches user data from a sample API and prints the user's name. It uses async/await to wait for the network response and handles errors if the fetch fails.
Node.js
import fetch from 'node-fetch'; async function getUser() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); const user = await response.json(); console.log(`User name: ${user.name}`); } catch (error) { console.error('Failed to get user:', error); } } getUser();
OutputSuccess
Important Notes
Always use try/catch blocks inside async functions to handle errors gracefully.
Remember that await only works inside functions marked with async.
Using async/await makes asynchronous code look like normal, easy-to-read code.
Summary
Async/await helps write clear code that waits for tasks without blocking.
Use async before functions and await before promises.
Handle errors with try/catch inside async functions.