ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
JavaScript Tutorial• 6 min read
Async JavaScript: Promises & Fetch
Working with asynchronous operations and calling REST APIs
"I Promise a Result!" - Asynchronous JavaScript enables code to perform time-consuming operations (like fetching network data) without freezing the user interface.
Understanding Promises and async/await
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
The async keyword placed before a function makes it return a Promise.
The await keyword makes JavaScript wait until the promise settles and returns its result.
The built-in fetch() method makes HTTP requests simple and clean.
Fetching Data with async/await
async function fetchUserData(username) {
try {
const response = await fetch(`https://api.github.com/users/${username}`);
if (!response.ok) {
throw new Error(`User not found (Status: ${response.status})`);
}
const data = await response.json();
console.log("User Bio:", data.bio);
console.log("Public Repos:", data.public_repos);
return data;
} catch (error) {
console.error("Failed to load user:", error.message);
}
}
// Call the async function
fetchUserData("octocat");ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Where can the "await" keyword be used in standard JavaScript?