Asynchronous operations are crucial in JavaScript for tasks that take time, such as fetching data, reading files, or making API calls. Traditional callback-based approaches led to callback hell and code that's hard to maintain.
Slide 1: Introduction to Asynchronous Operations Asynchronous operations allow JavaScript to perform non-blocking operations, meaning it can continue to execute other code while waiting for these operations to complete. Examples include API calls, timers, and reading files.
console.log("Start");
setTimeout(() => {
console.log("This is a timer");
}, 2000);
console.log("End");
Slide 2: Promises A Promise is an object representing the eventual completion or failure of an asynchronous operation. It returns a value which is either a resolved value or a reason why it’s rejected.
let promise = new Promise((resolve, reject) => {
let condition = true; // This can be any condition
if(condition) {
resolve("Promise is resolved");
} else {
reject("Promise is rejected");
}
});
Slide 3: Promise Methods Promises have methods like .then()
, .catch()
, and .finally()
to handle the resolved or rejected state.
promise
.then(value => console.log(value)) // "Promise is resolved"
.catch(error => console.log(error))
.finally(() => console.log("This will run irrespective of resolve or reject"));
Slide 4: Async/Await Async/Await is a syntactic sugar on top of Promises. An async
function returns a Promise, and the await
keyword is used to wait for the Promise.
async function asyncFunction() {
let response = await promise;
console.log(response); // "Promise is resolved"
}
asyncFunction();
Slide 5: Error Handling in Async/Await Errors in Async/Await can be handled using try/catch blocks.
async function asyncFunction() {
try {
let response = await promise;
console.log(response); // "Promise is resolved"
} catch(error) {
console.log(error);
}
}
asyncFunction();
Comments
Post a Comment