Chaining Promises
Notice how we had gone from this pattern (which exhibits callback hell)
console.log("listening for events");
getUser(1, (user) => {
getLoans(user["Account number"], (loans) => {
getTransactions(loans["Most recent"], (transactions) => {
console.log(transactions);
});
});
});
console.log("still listening for events!");
to this pattern which exhibits promise chaining:
console.log("listening for events");
getUser(1)
.then((user) => getLoans(user["Account number"]))
.then((loans) => getTransactions(loans["Most recent"]))
.then((transactions) => {
console.log(transactions);
});
console.log("still listening for events!");
In the first implementation we used callbacks and that is why we ended up with the nested structure (callback hell problem). In the second implementation we used Promises and we got a flat structure.
Since Promises expose
then
method we can chain them to implement a complex async operation.
As a good practice, whenever you work with Promises you must make sure to catch any errors.
console.log("listening for events");
getUser(1)
.then((user) => getLoans(user["Account number"]))
.then((loans) => getTransactions(loans["Most recent"]))
.then((transactions) => {
console.log(transactions);
})
.catch((error) => {
console.log(error); // probably need to do more than this!
});
console.log("still listening for events!");