Skip to content

Commit 574e4b0

Browse files
authored
Update 67-Chaining Promises.md
1 parent e40248a commit 574e4b0

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

notes/English/67-Chaining Promises.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,28 @@
1-
### what is Chaining Promises in javascript
1+
### Chaining Promises
2+
23
Chaining Promises in JavaScript is a technique for handling asynchronous operations where multiple Promise objects are linked together in a chain, with the output of one Promise becoming the input of the next. This allows for more efficient and readable code compared to nested callback functions. Each Promise in the chain can be modified or transformed using methods such as .then(), .catch(), and .finally() to handle success, error, and completion cases respectively.
4+
5+
Chaining promises in JavaScript allows you to execute asynchronous operations in a sequence, where the output of one operation feeds as input to the next one.
6+
7+
Here's an example:
8+
9+
```javascript
10+
fetch('https://jsonplaceholder.typicode.com/users')
11+
.then(response => response.json())
12+
.then(data => {
13+
console.log(data);
14+
return fetch(`https://jsonplaceholder.typicode.com/posts?userId=${data[0].id}`);
15+
})
16+
.then(response => response.json())
17+
.then(posts => console.log(posts))
18+
.catch(error => console.error(error));
19+
```
20+
21+
In this code, we start by performing a GET request to retrieve a list of users from a public API. We then parse the JSON response using the `json()` method, and extract the first user from the array.
22+
23+
Next, we use the extracted user's ID to construct a new URL, which we pass to another `fetch()` call to obtain a list of posts made by that user. Again, we parse the JSON response, and finally log the posts to the console.
24+
25+
If any errors occur while executing the promises, we catch them with the `catch()` method and log them to the console. The chain of promises ensures that each operation is executed in the correct order, without blocking the main thread, and that the output of one operation becomes the input of the next.
26+
27+
28+

0 commit comments

Comments
 (0)