Promises

Part 2

Posted by Nolan Hughes on November 5th, 2018

For part 2 of my Promises series I thought it’d be a good idea to go over error propagation. The main takeaways are using .catch and try and catch with aysnc/await. Using .catch at the end of a promise chain looks like the example below.

doSomething() .then(result => doSomethingElse(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => console.log(`Got the final result: ${finalResult}`)) .catch(failureCallback);

When you do this the chain will stop if there’s an exception because it then looks down the chain for a catch handler. An even nicer and more succinct way is to use aysnc/await with try and catch. This example is very reminiscent of synchronous code.

async function foo() { try { const result = await doSomething(); const newResult = await doSomethingElse(result); const finalResult = await doThirdThing(newResult); console.log(`Got the final result: ${finalResult}`); } catch(error) { failureCallback(error); } }

This is wrapped up in a super neat async function and catches all of your errors. Even thrown exceptions and programming errors! Being able to handle your errors is an essential part of writing clean code and for functional composition of asynchronous operations.