Chaining Promises

In the previous exercise, we changed the callback pattern (exhibiting the Christmas tree problem) 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!");

Promise chaining flattens the nested structure of callback hell.

As a good practice, whenever you work with Promises, end the chain with a catch block 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.message); // probably need to do more!
  });
console.log("still listening for events!");