This lesson covers
- What promises are and why they’re important
- The Deferred object
- How to manage multiple asynchronous operations
- Resolving and rejecting a promise
For a long time, JavaScript developers have used callback functions to perform several tasks such as running operations after a given amount of time (using set-Timeout()), or at regular intervals (using setInterval()), or to react to a given event (click, keypress, load, and so on). We’ve discussed and employed callbacks extensively to perform asynchronous operations; for example, in lesson 6 where we focused on events, in lesson 8 when we talked about animations, and in lesson 10 where we covered Ajax. Callback functions are simple and get the job done, but they become unmanageable as soon as you need to execute many asynchronous operations, either in parallel or in sequence. The situation where you have a lot of nested callbacks, or independent callbacks that have to be synchronized, is often referred to as the “callback hell.”
Today, websites and web applications are often powered by JavaScript code more than backend code only (this is the era of API-driven services, isn’t it?). For this reason, developers need a better way to manage and synchronize asynchronous operations to keep their code readable and maintainable.
In this lesson we’ll discuss promises, what they are, and how jQuery allows you to use them. Our lovely library implements promises (the concept) through the use of two objects: Deferred and Promise. How jQuery implements promises has been the subject of discussions, criticisms, and a lot of changes, as you’ll learn in the next pages.
While progressing through this lesson, you’ll note that the terminology might be confusing and that the concept of promises doesn’t map one to one with the Promise object, which admittedly is weird. You’ll also need to learn several new terms. Don’t be scared, though. The text is filled with several examples and extensive explanations that will help you with the learning process.
Leave a Reply