fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});10. Promise Utility Methods
Promise.all()
Waits for all promises to complete.
Promise.all([promise1, promise2])
.then(results => {
console.log(results);
});
Promise.race()
Returns the first completed promise.
Promise.race([promise1, promise2])
.then(result => {
console.log(result);
});
11. Async/Await
A cleaner way to work with Promises.
Example:
async function fetchData() {
const response = await fetch("https://api.example.com");
const data = await response.json();
console.log(data);
}Benefits:
• Cleaner syntax
• Easier to understand
• Better error handling
12. Error Handling with Async/Await
Use try...catch to handle errors.
Example:
async function fetchData() {
try {
const response = await fetch("https://api.example.com");
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}13. Fetch API
The Fetch API is used to make HTTP requests.
Example:
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
});14. setTimeout() vs setInterval()
setTimeout()
Runs once after a delay.
setTimeout(() => {
console.log("Executed");
}, 1000);setInterval()
Runs repeatedly at a fixed interval.
const interval = setInterval(() => {
console.log("Running");
}, 1000);
clearInterval(interval);15. Real-World Example
Fetch User Data
async function getUsers() {
try {
const response = await fetch("https://api.example.com/users");
const users = await response.json();
console.log(users);
} catch (error) {
console.log("Error:", error);
}
}Most Important Interview Topics
Call Stack, Callback Queue, Event Loop, Callback Functions, Callback Hell, Promises, Promise Chaining, Promise.all(), async/await, Fetch API, Error Handling
Practice Questions
Easy
• Print a message after 3 seconds
• Use setInterval() to print numbers
Medium
• Fetch data from a public API
• Display loading text while fetching data
Advanced
• Implement a custom Promise.all()
• Retry failed API requests
• Fetch multiple APIs in parallel using Promise.all()
Double Tap ❤️ For More