Master asynchronous programming with Promises and async/await syntax.
async/await
, simplifying asynchronous code and making it appear synchronous.
Here's an example showing both Promises and async/await in action:
// Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
fetchData().then(data => {
console.log("Promise:", data);
}).catch(error => {
console.error(error);
});
// Using Async/Await
async function getData() {
try {
const result = await fetchData();
console.log("Async/Await:", result);
} catch (error) {
console.error(error);
}
}
getData();
This code demonstrates:
.then()
and handling errors with .catch()
.async
functions.await
.A Promise represents a value that may be available now, or in the future, or never. It has three states: pending
, fulfilled
, and rejected
.
resolve()
is called when the async task succeeds.reject()
is used when the task fails.Async/Await is syntactic sugar over Promises, enabling you to write asynchronous code that looks synchronous.
async
before a function makes it return a Promise.await
can only be used inside async
functions and waits for the Promise to resolve.fetch()
or axios
.Q1: What are the three states of a JavaScript Promise?
Answer: C. Pending, Fulfilled, Rejected
Q2: What does the await
keyword do?
Answer: C. Waits for a Promise to resolve
Q3: Which keyword is used to define an async function?
Answer: C. async
Q4: Which method is used to handle errors in a Promise?
Answer: B. .catch()