For years, asynchronous JavaScript relied heavily on callbacks and promises (.then()). The introduction of async/await made non-blocking code far easier to read and write.
From Promises to Async/Await
Instead of chaining .then() calls, the await keyword pauses execution until the promise resolves, yielding clean, synchronous-looking code.
async function fetchUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error('User not found');
}
const data = await response.json();
console.log('User data:', data);
} catch (error) {
console.error('Error:', error.message);
}
}
0 Comments