An addendum to my so-called expertise

In August I delivered a presentation called “Mastering Asynchronous Flow Control in JavaScript” at devLink 2014. To illustrate how tricky mixing asynchronous and synchronous code in JavaScript can be, I gave the following example:

bad, bad example

I claimed, incorrectly, that the error thrown in the callback would cause unintended consequences when it re-entered the catch block (well, beyond just crashing the program).

I have since had a chance to re-visit this code and realized that this example is not representative of the point I wanted to make, which is actually represented by this gist:

In this example, an async function is invoked with a callback. Inside that function a try/catch block is executed, and when successful, invokes the callback within the try block. When the callback itself throws an exception it bubbles back up into the try block and then gets caught in the catch block, invoking the callback a second time. You can see this in the console output, where the first logged arguments object contains a null error and the second contains the error thrown in the callback itself. To avoid this situation simply invoke the callback outside of the try/catch block altogether:

Now I shall go into the East and diminish.

Leave a Reply

Your email address will not be published. Required fields are marked *