Async/await is a modern way to handle asynchronous operations in Node.js,
making code more readable and easier to maintain compared to traditional callback-based code. Async/await is built on top of promises, which provide a way to handle asynchronous operations in a more organized manner
Inside an async function, you can use the await
keyword to pause the execution of the function until a promise is resolved
const axios = require('axios');
// Function to fetch user data asynchronously
async function fetchUserData(userId) {
try {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${userId}`);
return response.data;
} catch (error) {
console.error('Error fetching user data:', error);
}
}
// Using async/await to fetch user data
async function main() {
const userId = 1; // You can change this to any user ID you want to fetch
const userData = await fetchUserData(userId);
if (userData) {
console.log(`User data for user with ID ${userId}:`, userData);
}
}
// Call the main function
main().catch(console.error);
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex