Asynchronous JavaScript Patterns
Introduction: Moving From Sync To Async
In our previous lessons, we explored the world of Symbols and Generators. We learned how to build lazy pipelines that process data only when we ask for it. While those pipelines are powerful, they are usually synchronous. This means the computer performs each step of the calculation immediately, one after another, without waiting for outside forces.
However, in real-world programming, we often have to deal with tasks that take an unpredictable amount of time. You might need to fetch a user's profile from a database, download an image from a website, or simply wait for a specific amount of time to pass. If we handled these tasks synchronously, our entire program would "freeze" until the task finished. To keep our applications smooth and responsive, we use Asynchronous JavaScript. In this lesson, we will learn how to manage these time-based tasks using Promises and the modern async/await syntax.
Creating Promises With Resolve And Reject
The foundation of asynchronous JavaScript is the Promise. You can think of a Promise as a placeholder for a value that does not exist yet but will be available in the future. When we create a new Promise, we provide a function that tells the Promise how to behave. This function receives two special tools: resolve and reject.
We call resolve when a task finishes successfully, passing along the result. We call reject if something goes wrong, passing along an error. Let’s look at two helper functions that use the setTimeout timer to simulate these outcomes. The delay function creates a Promise that succeeds after a few milliseconds, while the fail function creates a Promise that intentionally fails.
In the delay function, we pass the ms (milliseconds) to setTimeout. Once that time passes, the code inside runs and calls resolve(value). This "fulfills" the Promise with the data we provided. In the fail function, we use the second argument of the Promise constructor, which is reject. After the time passes, it creates a new Error object and rejects the Promise, signaling that the operation failed.
Consuming Promises With .then() and .catch()
