0% found this document useful (0 votes)
6 views

notes

The document explains the use of preventDefault() to stop default event behaviors and introduces async/await in JavaScript for handling asynchronous operations more cleanly. It details the async keyword for defining asynchronous functions that return Promises, the await keyword for pausing execution until a Promise resolves, and error handling with try...catch. Additionally, it discusses parallel execution with Promise.all() and highlights the benefits of improved readability and simplified error handling in asynchronous code.

Uploaded by

sumit78599
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

notes

The document explains the use of preventDefault() to stop default event behaviors and introduces async/await in JavaScript for handling asynchronous operations more cleanly. It details the async keyword for defining asynchronous functions that return Promises, the await keyword for pausing execution until a Promise resolves, and error handling with try...catch. Additionally, it discusses parallel execution with Promise.all() and highlights the benefits of improved readability and simplified error handling in asynchronous code.

Uploaded by

sumit78599
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

preventDefault:- preventDefault()

means that when an event occurs (e.g.


button click, form submit, or keyboard
press), to prevent the default behavior of
our event. When you use
preventDefault(), you prevent the browser
or any other software from performing our
action.

Async and Await:-


Theory of async and await in JavaScript

async and await are used to handle asynchronous operations in JavaScript in a cleaner and
more readable way, making asynchronous code behave more like synchronous code.

1. async Keyword

 Purpose: The async keyword is used to define an asynchronous function.


 Return Value: An async function always returns a Promise, which is either resolved
with the return value of the function or rejected if an error is thrown.
 Function Behavior: Even though an async function executes asynchronously, the
result is handled like a regular function but with Promise-based behavior.

Key Points:

 The async keyword ensures that the function returns a Promise, even if the function
does not explicitly return a Promise.
 It allows for the use of the await keyword inside the function.

Example:

async function example() {


return "Hello, World!";
}

example().then((result) => console.log(result)); // Outputs: "Hello,


World!"

2. await Keyword
 Purpose: The await keyword is used inside async functions to pause execution until
a Promise is resolved or rejected.
 Behavior: When await is used, the function execution is paused, and JavaScript
waits for the Promise to settle before proceeding.
 Promise Resolution: If the Promise resolves successfully, the resolved value is
returned. If the Promise rejects, an error is thrown.

Key Points:

 await can only be used inside functions declared with async.


 The await keyword makes JavaScript behave as if it’s executing the asynchronous
code synchronously, improving readability and maintainability.

Example:

async function example() {


let result = await Promise.resolve("Hello");
console.log(result); // Outputs: "Hello"
}

example();

3. Working of async/await Together

 async makes the function return a Promise.


 await pauses the execution until the Promise resolves or rejects.
 After the Promise resolves, the result is available, and the function continues
executing from where it was paused.

4. Error Handling with async/await

 Errors in async functions can be handled using the traditional try...catch


mechanism.
 If a Promise rejects, the error can be caught by catch.

Key Points:

 Synchronous-like Error Handling: Using try...catch allows errors to be handled


as if the code is synchronous, making it easier to manage asynchronous errors.

Example:

async function fetchData() {


try {
let response = await
fetch('https://jsonplaceholder.typicode.com/posts');
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();

5. Parallel Execution with async/await

 await pauses the function execution until a Promise is resolved, which can lead to
sequential execution.
 However, multiple asynchronous operations can be executed in parallel by calling
multiple Promises and using Promise.all().

Key Points:

 Promise.all(): This method ensures that all promises execute concurrently and only
resolves when all promises have resolved.

Example:

async function fetchData() {


const userData = await
fetch('https://jsonplaceholder.typicode.com/users');
const postData = await
fetch('https://jsonplaceholder.typicode.com/posts');

const [users, posts] = await Promise.all([userData.json(),


postData.json()]);
console.log(users, posts);
}

fetchData();

6. Important Considerations

 Blocking: Although await waits for promises, it only blocks the execution of the
code inside the async function. Other asynchronous tasks continue in parallel.
 await and Non-Promise Values: If a non-Promise value is passed to await, it is
treated as a resolved Promise immediately.
 Return Value of async Functions: The return value of an async function is always a
Promise, even if it doesn’t explicitly return one.

7. Benefits of Using async/await

 Improved Readability: Asynchronous code using async/await looks more like


synchronous code, making it easier to read and understand.
 Error Handling: Easier to handle errors in asynchronous code through try...catch
blocks, similar to synchronous code.
 Cleaner Code: Eliminates the need for complex chaining of then() and catch() that
is common with Promises.

Summary

 async: Marks a function as asynchronous, making it return a Promise.


 await: Pauses the execution of an async function until the Promise resolves or
rejects.
 Error Handling: async/await simplifies error handling using try...catch.
 Parallel Execution: Promise.all() can be used to execute multiple asynchronous
tasks in parallel.

async/await helps make JavaScript asynchronous code more manageable and readable by
simplifying the handling of Promises and providing a more synchronous-like flow of
execution.

You might also like