Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Promise chaining is a mechanism where each .then() returns a new promise, allowing you to build a chain of asynchronous operations.
Essentially, this means that the result of one .then() is passed to the next .then() until the final result is reached.
fetch("/user.json")
.then(response => response.json()) // promise #1
.then(user => fetch(`/users/${user.id}`)) // promise #2
.then(response => response.json()) // promise #3
.then(userData => console.log(userData)) // promise #4
.catch(error => console.error(error)); // error handling
Here each
.then()returns a new promise, and the next.then()waits for its completion — this is called promise chaining.
.then() always returns a promise, even if return isn't explicitly specified..then(), it will automatically be wrapped in a promise..then() — it will be passed to the nearest .catch().fetch("/user.json").then(response => {
response.json().then(user => {
fetch(`/users/${user.id}`).then(response => {
response.json().then(userData => {
console.log(userData);
});
});
});
});
Such "nested" use of promises is called "callback hell" and makes code harder to read and maintain.
fetch("/user.json")
.then(res => res.json())
.then(user => fetch(`/users/${user.id}`))
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
.then() correctly: return promises to create chains.Fact:
async/await is syntactic sugar over Promise chaining.