JavaScript Async & Promises

Pascual Vila
Senior Developer // Code Syllabus
JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language. But what does that actually mean for your code? It means you need to master Promises and Async/Await to build smooth, modern web apps.
The Synchronous Problem
By default, JS executes line by line. If line 2 requires fetching 10MB of data from an API synchronously, line 3 will not run until the download finishes. During this time, the entire browser tab freezes. The Event Loop is blocked, and user clicks are ignored.
Callbacks to Promises
Initially, we solved this by passing callbacks (functions to run later). But complex flows led to deep nesting known as Callback Hell. ES6 introduced Promises. A Promise represents a value that is unknown now, but will be resolved in the future. Instead of nesting, you chain .then() and .catch() methods.
Enter Async / Await
ES2017 gave us syntactical sugar over Promises: async and await. By placing await in front of a Promise, the function pauses its execution until the Promise resolves, while leaving the main thread unblocked. It allows async code to read like standard synchronous code, wrapped elegantly in try/catch blocks for error handling.