Promise Chaining Javascript
- Promise chaining is the practice of attaching multiple
.then() handlers to a promise to handle sequential asynchronous operations in a cleaner, more readable manner.
- Each
.then() in the chain is executed after the previous promise is resolved, and it passes the result to the next .then()
- Each operation depends on the previous one & errors can be handled in a single
.catch()
- Avoids Callback Hell Javascript
Example
getUserData(userId)
.then(user => getPosts(user)) // Pass user to getPosts
.then(posts => getComments(posts)) // Pass posts to getComments
.then(comments => { //
console.log(comments); // Do something with comments
})
.catch(error => console.error(error));// Handle any errors