Before you go, check out these stories!

0
Hackernoon logoExploring Differences Between Promises And Callbacks in JavaScript by@christianotieno

Exploring Differences Between Promises And Callbacks in JavaScript

Author profile picture

@christianotienoChristian Otieno

Software Developer

You might have heard what a Promise is or what Callback functions are in JavaScript. Clarity is needed when distinguishing between these two functions more so, when working with APIs in JavaScript-based applications.

JavaScript is the language for the web. And when working with functions, not all of them will behave in the same way. Some will always be reliable (they always return the same thing). I tend to call them pure functions. Others will tend to behave differently. Good examples are those that will at times, take time to complete when doing tasks. The tasks could be such as fetching data from a server to render it on a page. These functions in JavaScript, are referred to as asynchronous. They are what we will be looking at.

Asynchronous Functions

For us to truly understand the differences between Callbacks and Promises, we should get to know what they are first and foremost. These are asynchronous functions. And as explained briefly in the introduction, they are functions that work in the background while the rest of your code executes.

Let’s take, for instance, call made to an API to get some data. The way the web works is that there are going to be some rounds (journeys) made in retrieving the data from the remote server. The process in itself is most likely to take some time. The results may not be instant, not like in the case of a pure function that expects to return an expected value when it immediately gets invoked.

The result in the case of an asynchronous function, when talking to an API, for instance, could be anything. It could be a 404, a 201, or any other message wrapped inside of an HTTP status code. More about status codes here. So, it is not guaranteed that you will get what you requested and at the exact moment.

The scenario, in this case, could lead to some issues that might affect the working of the entire code. That’s where asynchronous functions come in. They help solve the uncertainties that might bring about these eventualities.

Talking to an API is one of the works asynchronous function does well. In this case, while it is happening, it can instruct the program not to wait on it and be doing other things in the meantime, as they finish executing their mandate. These functions can be programmed to do a lot of other things. I just chose a scenario of them interfacing with APIs to showcase how they work.

What are Callbacks?

Not so long ago, asynchronous functionality could only be best accomplished, with the nesting of multiple callbacks to achieve the intended purpose.

A callback function herein can be defined as a function that gets passed into another function as an argument. It will then get invoked inside the outer function to complete some given routine or action. MDN

The definition can further get explained in the snippet below:

button.addEventListener("click", function(){
  // do something!
})

What is happening here is that we have a function called addEventListener() This function gets passed in a callback (in this case ‘do something’ function) and then calls it when the button gets clicked.

The pattern described above is often used a lot with JavaScript developers. Unfortunately, though they are useful in situations like the above example, using callbacks can get out of hand, especially when you need to chain several of them together in a specific order. And it may lead to a situation fondly or dreadfully known by most JavaScript developers as the Callback hell.

What are Promises?

As established earlier, we are dealing with the language of the web. It is now clear what callbacks are and how they can be used.

Promises are not different if anything they help with not getting stuck in the callback hell or avoid it altogether if you’d prefer them over callbacks. They are also popularly used, and chances are nearly all if not most of the libraries and frameworks employ them.

They are objects in JavaScript that might produce a value in the future. They allow you to associate handlers with an asynchronous action’s eventual success value or failure reason MDN.

Okay, what does all this mean? You may ask. The definition is just a fancy way of explaining the inner working of Promises in Js. Natively put, an object in JavaScript is a ‘key-value’ pair type of a data structure.

More about objects here or if you prefer watching videos, these series by mmtuts will do you good.

‘To return a value in the future’ can be broken down to an asynchronous function. Herein, a Promise, that tells the rest of your code to execute while it is working in the background. But they do it so neatly in alerting the program on what is going on. Unlike Callbacks, they will have three states, pending, fulfilled or rejected.

Pending is always the initial state. Nothing much going on here. Fulfilled is the status where the operation has completed successfully. Rejected will indicate a failed execution. Thereby you are always bound to know where the program is having issues.

Consider the snippet below:

const getProfile = function() {
  // fetch data from API...
  // clean it up and return it as an object:
  return data
}
const myData = getProfile() // if this is refactored to return a Promise...
myData.then(function(data){ // .then() tells it to wait until the promise is resolved
  const pieceOfData = data['something'] // and THEN run the function inside
})

What’s happening here is that, in the first instance, getProfile() function, if called, will fetch some data from a server and return it as an object that gets used in the code.

The rest of the instances are telling on the program that it should wait until the Promise finishes to fetch data. In this case, the program does not get the chance of running into problems with returning undefined data should it call the Promise while it is still fetching.

Conclusion…

Asynchronous functions are a cool thing to master. Callbacks are great but can at times prove inefficient to use. Promises, on the other hand, are efficient to use and allows you to do more with fewer lines of code.





Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!