|
1 |
| -# Module 1: Advanced JavaScript Concepts |
| 1 | +## Module 1: Advanced JavaScript Concepts |
| 2 | +### 1.2. Promises and Async/Await |
2 | 3 |
|
3 |
| -## 1.2. Promises and Async/Await** |
| 4 | +Promises and the async/await syntax are critical concepts in modern JavaScript for managing asynchronous operations. They simplify asynchronous code and make it more readable and maintainable. Let's explore these concepts in depth with examples: |
4 | 5 |
|
5 |
| -**Description:** |
| 6 | +#### Promises: |
| 7 | +Promises are objects that represent the eventual completion or failure of an asynchronous operation. They provide a way to work with asynchronous code in a more structured and organized manner. |
6 | 8 |
|
7 |
| -Promises and Async/Await are crucial concepts in modern JavaScript, specifically designed to handle asynchronous operations more efficiently and readably. This section explores these concepts and their applications in detail. |
| 9 | +A promise can be in one of three states: |
8 | 10 |
|
9 |
| -**Topics Covered:** |
| 11 | +1. **Pending:** The initial state, representing that the operation has not yet completed. |
| 12 | +2. **Fulfilled:** The state when the operation has succeeded, and a result is available. |
| 13 | +3. **Rejected:** The state when the operation has failed, and an error reason is available. |
10 | 14 |
|
11 |
| -- **Promises:** Promises are a way to manage asynchronous operations and provide a cleaner alternative to callback functions. You'll learn how to create, use, and chain promises to handle asynchronous tasks effectively. |
| 15 | +**Example: Using Promises** |
12 | 16 |
|
13 |
| -- **Promise States:** Promises have three states: pending, fulfilled, and rejected. Understanding these states is essential for managing asynchronous operations gracefully. |
14 |
| - |
15 |
| -- **Error Handling:** Promises allow for streamlined error handling using `.catch()` and handling errors within the promise chain. |
16 |
| - |
17 |
| -- **Async/Await:** Async/Await is a more recent addition to JavaScript, simplifying asynchronous code even further. You'll explore how to write asynchronous code that looks like synchronous code and effectively use `async` functions and the `await` keyword. |
18 |
| - |
19 |
| -- **Parallel and Sequential Execution:** You'll learn how to orchestrate multiple asynchronous operations, executing them in parallel or sequentially, depending on your requirements. |
| 17 | +```javascript |
| 18 | +function asyncOperation() { |
| 19 | + return new Promise((resolve, reject) => { |
| 20 | + setTimeout(() => { |
| 21 | + const result = Math.random(); |
| 22 | + if (result >= 0.5) { |
| 23 | + resolve(result); // Resolve with a result |
| 24 | + } else { |
| 25 | + reject("Operation failed"); // Reject with an error |
| 26 | + } |
| 27 | + }, 1000); |
| 28 | + }); |
| 29 | +} |
20 | 30 |
|
21 |
| -**Practical Application:** |
| 31 | +asyncOperation() |
| 32 | + .then(result => { |
| 33 | + console.log("Operation succeeded with result:", result); |
| 34 | + }) |
| 35 | + .catch(error => { |
| 36 | + console.error("Operation failed with error:", error); |
| 37 | + }); |
| 38 | +``` |
22 | 39 |
|
23 |
| -Promises and Async/Await are extensively used in modern web development for handling tasks like making API requests, reading/writing files, and managing concurrent operations. They improve code readability and maintainability, making asynchronous code easier to work with. |
| 40 | +In the example above, we create a promise that simulates an asynchronous operation and resolves or rejects based on a random number. We then use `.then()` to handle success and `.catch()` to handle errors. |
24 | 41 |
|
25 |
| -**Examples:** |
| 42 | +#### Async/Await: |
| 43 | +The async/await syntax provides a more readable and synchronous-like way to work with promises. The `async` keyword is used to declare an asynchronous function, and the `await` keyword is used inside such functions to pause the execution until a promise is resolved. |
26 | 44 |
|
27 |
| -Here's an example of using Promises and Async/Await to fetch data from an API: |
| 45 | +**Example: Using Async/Await** |
28 | 46 |
|
29 | 47 | ```javascript
|
30 |
| -// Using Promises |
31 |
| -fetch('https://api.example.com/data') |
32 |
| - .then((response) => { |
33 |
| - if (!response.ok) { |
34 |
| - throw new Error('Network response was not ok'); |
35 |
| - } |
36 |
| - return response.json(); |
37 |
| - }) |
38 |
| - .then((data) => { |
39 |
| - console.log(data); |
40 |
| - }) |
41 |
| - .catch((error) => { |
42 |
| - console.error('There was a problem:', error); |
43 |
| - }); |
44 |
| - |
45 |
| -// Using Async/Await |
46 |
| -async function fetchData() { |
| 48 | +async function performAsyncTask() { |
47 | 49 | try {
|
48 |
| - const response = await fetch('https://api.example.com/data'); |
49 |
| - if (!response.ok) { |
50 |
| - throw new Error('Network response was not ok'); |
51 |
| - } |
52 |
| - const data = await response.json(); |
53 |
| - console.log(data); |
| 50 | + const result = await asyncOperation(); |
| 51 | + console.log("Operation succeeded with result:", result); |
54 | 52 | } catch (error) {
|
55 |
| - console.error('There was a problem:', error); |
| 53 | + console.error("Operation failed with error:", error); |
56 | 54 | }
|
57 | 55 | }
|
58 | 56 |
|
59 |
| -fetchData(); |
| 57 | +performAsyncTask(); |
60 | 58 | ```
|
61 | 59 |
|
62 |
| -**Key Takeaways:** |
| 60 | +In this example, we declare an `async` function `performAsyncTask`, which uses `await` to pause until the `asyncOperation` promise is resolved or rejected. This makes the code look more synchronous and easier to read. |
| 61 | + |
| 62 | +#### Practical Uses: |
| 63 | +Promises and async/await are widely used in JavaScript for various asynchronous tasks, including: |
| 64 | + |
| 65 | +1. **HTTP Requests:** Promises are often used to manage AJAX requests, making it easier to handle responses. |
| 66 | + |
| 67 | +2. **Timeouts and Intervals:** Promises are useful for scheduling tasks to run after a specified time interval. |
| 68 | + |
| 69 | +3. **File I/O:** Promises simplify reading and writing files in Node.js applications. |
| 70 | + |
| 71 | +4. **Database Queries:** Promises make it easier to work with databases and manage queries. |
| 72 | + |
| 73 | +5. **Parallel and Sequential Execution:** Async/await allows you to control the flow of asynchronous operations, whether they need to run in parallel or sequentially. |
63 | 74 |
|
64 |
| -Promises and Async/Await are essential tools for managing asynchronous operations in JavaScript. They simplify error handling, improve code readability, and are widely used for tasks involving network requests, file I/O, and more. Understanding these concepts is crucial for modern web development. |
| 75 | +Promises and async/await have become integral tools for handling asynchronous operations in JavaScript, improving code readability and maintainability while reducing callback hell. |
0 commit comments