Chapter 10
Keeping Your Promises

Asynchronous programming is a way of life in JavaScript. Unless a method returns instantaneously, we should never call it with the intention of waiting for a response. Most functions in JavaScript libraries and frameworks are asynchronous. Although making a call and getting the results later is not new in JavaScript, the mechanics of this have evolved over the past few years.

The traditional approach to asynchronous programming was to use callbacks. Unfortunately, as we’ll soon discuss, there are many issues with callbacks. In modern JavaScript, promises replace callbacks for asynchronous programming. A code that returns a promise is nonblocking and will eventually return a result or an error to the caller through the promise.

Although legacy libraries still use callbacks, that approach is the least desirable. As we’ll see, there are libraries to convert callbacks into promises.

Newer functions rely on promises, which are easier to work with compared to callbacks; their structure is a lot like the structure in the functional style of programming. Promises are much better not only for propagating errors, but in recovering from them as well. We’ll explore various ways to work with promises in this chapter.

Promises are arguably better than callbacks, but there’s a bit of ceremony in using them. When compared to the structure of synchronous imperative style code, they are different and require some planning. There are benefits to keeping the code structure the same for both synchronous and asynchronous programming—that’s where async and await come in. By the end of this chapter, you’ll know how promises can be extended to use the new async and await.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset