CHAPTER 6 Ensuring Correct Use of the Promise Pattern
WHAT’S IN THIS CHAPTER?
- Using and testing Promises
- Understanding Promise states and fates
- Constructing Promises
- Testing a Promise-wrapped XMLHttpRequest
- Chaining Promises
- How “Deferred” libraries handle advanced scenarios in Promise testing
- A caution about jQuery promises
WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
The wrox.com code downloads for this chapter are found at www.wrox.com/go/reliablejavascript
on the Download Code tab. The code is in the Chapter 6 download and individually named according to the filenames noted throughout this chapter.
The last chapter illustrated how to code and test (or, more correctly, test and code) the Callback Pattern. In the main example, checkInService.checkIn(attendee)
was used as a callback function in iteration through all attendees to check them into a JavaScript conference. This chapter will extend that feature, adding error handling and asynchronous processing.
Although this could be done with JavaScript events, ECMAScript 6 has introduced a better way: the Promise
object. If you must support older browsers, polyfills are available.
UNDERSTANDING PROMISES THROUGH UNIT TESTS
A Promise
is an object that encapsulates an asynchronous operation and what to do upon its eventual outcome. When the operation completes, a callback encapsulated in the Promise
will be invoked. Actually, there can be two callbacks: one for success and one for failure. (The first callback does not ...
Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language 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.