Lesson 36
Promises
Throughout this book, you have made extensive use of callback functions. You have used callback functions:
- To register event listeners that fire when specific events occur
- To listen for the completion of
IndexedDB
operations, such as the insertion of data or the opening of the database - When using the JavaScript
filter
,map
, andreduce
functions to process arrays - When listening for messages from web workers
- When waiting for AJAX responses
As you can see, callback-based programming is enormously important to many JavaScript APIs, and it is impossible to gain a solid understanding of JavaScript without understanding callback functions.
Although callback-based APIs are enormously popular, they do bring their own set of problems. These problems are often referred to as “Callback hell” and stem largely from the following issues:
- It is often necessary to nest callbacks inside other callbacks, and this nesting can extend to several levels. As this happens, code can become difficult to read because it is not always obvious where each level of nesting ends.
- It is difficult to determine the behavior of an application because it is not possible to logically follow code with your eye.
- Data scoping can become difficult with callbacks. You can see this primarily in relation to the identity of
this
and the corresponding necessity to usebind
on each callback to ensure the correctthis
instance was set.
This lesson examines an alternative mechanism for implementing callback ...
Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.