Oct 26, 2018

Asynchronous JavaScript

First callbacks, then the Promise/A+ specification emerged followed by generator functions and now the async functions.

To achieve asynchronous programming, every asynchronous operation had to be handled with a callback. If you pass a function to another function (a.k.a. higher order function) as a parameter, within the function you can call it when you are finished with your job. No return values, only calling another function with the values.

The challenges with callbacks:
  • it is easy to build callback hells or spaghetti code with them if not used properly
  • error handling is easy to miss
  • can't return values with the return statement, nor can use the throw keyword
One of the answers was the async module. If you worked a lot with callbacks, you know how complicated it can get to run things in parallel, sequentially or even mapping arrays using asynchronous functions. 

Promises

A promise represents the eventual result of an asynchronous operation. In reality, promises are the foundation of the future of asynchronous programming in JavaScript. Ideally, promises will be tucked away behind the scenes and we'll be able to write our asynchronous code as if it were synchronous.

Generators / yield

JavaScript Generators is a relatively new concept, they were introduced in ES6 (also known as ES2015).

Async / await

Async functions were introduced in ES7 - and currently only available using a transpiler like babel. (disclaimer: now we are talking about the async keyword, not the async package)