Chapter 2. Introducing Promises
The biggest challenge with nontrivial amounts of async JavaScript is managing execution order through a series of steps and handling any errors that arise. Promises address this problem by giving you a way to organize callbacks into discrete steps that are easier to read and maintain. And when errors occur they can be handled outside the primary application logic without the need for boilerplate checks in each step.
A promise is an object that serves as a placeholder for a value. That value is usually the result of an async operation such as an HTTP request or reading a file from disk. When an async function is called it can immediately return a promise object. Using that object, you can register callbacks that will run when the operation succeeds or an error occurs.
This chapter covers the basic ways to use promises. By the end of the chapter you should be comfortable working with functions that return promises and using promises to manage a sequence of asynchronous steps.
This book uses the Promise API for the version of JavaScript known as ECMAScript 6 (ES6.) However, there were a number of popular JavaScript Promise libraries that the development community created before ES6 that may not match the spec. These differences are mostly trivial so it is generally easy to work with different implementations once you are comfortable using standard promises. We discuss API variations and compatibility issues with other libraries in Chapter 4.
Basic ...
Get JavaScript with Promises 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.