If you’ve worked with asynchronous programming in JavaScript before you might have already spotted why we’re not going to get a quote from this code. If that’s the case then high five.

Running it with node app.js you’ll quickly see undefined printed out.

Why does this happen?

The reason that the quote variable is undefined is because the callback function that assigns it is not called until after the call to the request function is finished. But because the request function executes asynchronously, JavaScript does not wait around for it to finish. Instead, it moves on to the next statement which returns the unassigned variable. For a great explanation on how async in JavaScript works under the hood check out this amazing talk by Philip Roberts at JSConf EU.

Synchronous code is generally easier to understand and write because everything executes in the order in which it is written. Return statements are widely used and pretty intuitive in other languages but unfortunately we’re unable to use them as much as we’d like in JavaScript because they don’t work well with JavaScript’s asynchronous nature.

So why go through the struggle of battling asynchronous code? Performance. Network requests and reading from the disk are what we call I/O (input/output) operations. In synchronous I/O execution the program blocks, sitting around and waiting for data transmission to complete. If it takes 60 seconds for a database query to finish the program is sitting around doing nothing for 60 seconds. However during an asynchronous I/O operation the program can resume normal execution and deal with the results of the I/O operation whenever they come up. This is why callback functions exist but callbacks are far more difficult to work with and grok when reading the source of an application.

Utopia

Can we get the best of both worlds – asynchronous code that lets us work with blocking operations but is also easier to read and write? The answer is yes thanks to the ES7 proposal for Asynchronous Functions (Async/Await).

When a function is declared as async it is then able to yield execution to the calling code while it await s for a promise to be resolved. If you’re not familiar with promises check out one of these great resources.