Callbacks VS Promises – Differences – Simple Notes

I thought to discuss simply the differences between callbacks and promises in JavaScript and why promises are becoming so popular.

The classic callback pattern

This is a very standard callback pattern. You work with the data and when done you call the callback function.

In the callback you check if there is an error and if not, you process the success. It works and has worked for a while, but there are a few problems with this pattern.

First, you have duplication by having to call the callback function for both a success case and a error case.

Second, you have one function handling multiple cases – the callback has to manually check if there is an error and handle it. Every time you need to manually do that and the code starts to look messy and confusing the more you add.

Third, you can end up (for whatever reason) calling the callback function multiple times for either success or errors. This can cause all sorts of issues.

Promises

In promises it works similar to callbacks but we start by actually creating a new Promise();. Promises take two parameters – resolve and reject to handle respectively success and error cases.

You can call each only once and this is a much cleaner way, there are no assumptions (“undefined” means error).

Next, the promise function is called and it has a method available called .then(); The first parameter of .then() always handles the success so you know you will receive whatever you were expecting (in this case our JSON object “data”). The second parameter of .then() handles fails, hence the “error” is passed to receive the respective error.

You could achieve this pattern yourself as well, but promises provide a secure and intuitive way of handling callbacks.

Conclusion

Promises are great as they provide an easy, simple and secure way to handle callbacks in ES6, that is readable and just makes sense. If you want to read more on promises, check this article by Jake Archibald on developers.google.com.

Subscribe to receive the next post in your mailbox

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *