Let’s begin with a story.
You are creating an image gallery dedicated to steak lovers around the world. As a way of adding a little spice to the presentation, you decide to allow five steaks to fade onto the screen, one after another. In order to achieve this, you’ll want to make sure that the images are successfully loaded before you attempt to animate each one.
Let’s see how this will look when you try to chain a series of nested callback functions. We assume that a function named “animateImage()” will be called after the image has been successfully loaded.
Something seems wrong here. The code is starting to look real ugly.
Imagine if you had to debug five, six, seven, or even ten nested callbacks, each with its own layer of complexity. That would be absolutely terrifying.
Welcome to “callback hell”.
Looking at the code above, there are tons of repetition in error handling and way too many brackets. Is there a better way to handle such a request?
Thankfully, ES6 has given us the power of Promises, which allow us to rid the callback nesting that can occur when multiple asynchronous requests need to be made that also happen to depend on the outcome of each other.
Here’s the original callback function refactored and utilizing Promises.
We see that the function is now returning a new Promise object. Its constructor has two arguments: resolve and reject. As you might have guessed, a resolved Promise returns the unravelled value while a rejected Promise will return an error.
Once you have a reference to a Promise object, you can call the “.then()” method to carry out an action if the Promise has been resolved.
The resulting code is much easier to read, understand, and debug.
Does this mean that all callbacks should be replaced with Promises? Probably not.
As a general rule of thumb, it is best if you use the right tool for the job. Promises shine when you need to make asynchronous requests that depend on multiple other asynchronous requests. If you ever find yourself chaining endless callbacks back to back, you may need to give your eyes a little rest and break out the Promises!