Asynchronous Programming in JavaScript

Learn the need for applying the reactive paradigm based on the shortcomings of existing JS asynchronous approaches.

Introduction to JavaScript asynchronous programming

To understand what problems can be solved by applying the reactive paradigm, you must first understand different ways of executing asynchronous tasks in Javascript and their shortcomings. With this knowledge, you can arrive at a point where you feel that applying a reactive pattern is the best way to do asynchronous tasks.

First things first, JavaScript is a single-threaded language, which means that all the logic can be executed in a single thread, and if that logic contains long-running operations, like I/O access or HTTP calls, the other logic and the application’s UI will remain blocked until those long-running operations are resolved. For this reason, the concept of asynchronous programming was introduced. It all started with callback functions, which later moved to promises, and lastly to async/await. It’s worthwhile to understand these concepts as well as their pros and cons before shifting our focus towards the reactive paradigm.

Asynchronous programming with callbacks

The most common way to ensure that your code runs smoothly without blocking function is by passing callback functions to the long-running tasks, like I/O operations, mouse events, or HTTP calls, which are invoked after those tasks are finished.

mouseDownHandler = event => console.log('You clicked the mouse');
document.addEventListener('mousedown', mouseDownHandler)

Drawbacks

  1. Callback hell - nested callbacks, hard to manage
  2. Hard to combine HTTP requests
  3. Hard to include dependencies between callbacks - for example, several HTTP calls that need to be executed one after another, or creating drag and drop functionality or chaining mouse down and mouse move events

Get hands-on with 1200+ tech skills courses.