Introduction

Get introduced to asynchronous programming and the benefits of promises over callbacks.

Asynchronous programming

Asynchronous programmingAsynchronousProgramming is a way of life in JavaScript. Unless a method returns instantaneously, you 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.

Callback functions

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.

Promises vs callbacks

A code that returns a promise is nonblocking, and it will eventually return a result or an error to the caller through the promise.

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

Benefits of promises over callbacks

  • 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 for recovering from them as well. We’ll explore the various ways to work with promises in this chapter.

Get hands-on with 1200+ tech skills courses.