What’s so special about Promises in JS?
What are Promises in JavaScript? By definition based on the MDN reference.
“The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never.”
That’s cool. But what does this actually mean for you as a developer? Essentially all it means is Promises give you a more convenient, flexible of way of dealing with asynchronous operations when compared to traditional callbacks. More importantly however, they give you a more syntactically elegant way of dealing with error handling and event chaining. In other words Promises are JavaScript’s answer to what is affectionately known as ‘Callback Hell’
Promises can be implemented using multiple means, the promise object referred to by MDN relates specifically to the native Promise object that ships with ECMAScript6, however there are numerous implementations of promises available for download, two of the most popular being Q and Blackbird. There are also packages which include promise capability to provide specific functionality.
The best way to illustrate this is with an example. For the example we are going to compare how we would fetch data from an API using both traditional means with jQuery’s AJAX method and then with the promise based HTTP client Axios.
Here we have a very basic fortune cookie app, click the button, get your fortune,the left button is wired up to a jQuery and right button Axios.

Lets take a look at the code, comparing the standard Ajax ‘success’ callback with the Axios Promise based ‘.then’.

Okay, so as you can see we achieved the same asynchronous operation using both a Callback and Promise. The latter code is slightly more succinct and readable however I don’t blame if if you’re not quite impressed yet.
Where things get interesting is when we look at error handling and flow control. With Promises you can easily chain subsequent events regardless of the outcome of the initial operation.
So say we wanted to log out any errors from our API call if it happens to fail but still wanted subsequent operations to run despite the failure. We could catch our error, log it out and continue on down the chain with the next operation.

Want to do something like that using callbacks? Give it a shot and you will quickly understand how the term “Callback Hell” was coined.
So, the next time you find your self wrestling with asynchronous operations and callbacks, consider whether Promises would be a better fit for your use case.
Till next time!
J