Enough is Enough… Promises are not better than callbacks

Jibin Mathews
The Bit Theories
Published in
3 min readMar 16, 2018

--

If you are a JavaScript developer who thinks that Promises are the future of JavaScript or if you think that Promises are in anyway better than callbacks, then maybe you should rethink you being a “JavaScript developer”.

source: http://codeatmorning.com/

Let me get this straight…

Promises are not better than callbacks

Promises are not even a replacement for callbacks

I am a JavaScript developer and nope, I am not crazy. My friends had me tested.

Then why would I say the above sentences?

First of all, let us see how callbacks are defined. Clippings are from Mozilla.org website

And now for promises (Multiple snippets from the Mozilla org site):

Can you spot the difference?

Let me point out .

  1. A callback is FUNCTION which is passed as an ARGUMENT to another FUNCTION.
  2. A promise is an OBJECT or a PROXY for a FUNCTION whose value is not yet defined.

Need a stronger point?

This is the way someone would use callbacks:

function saveThisUser(userDetails){
const userObj = new User(userDetails);
userObj.save( (err, data) => {
if(err) return console.log(err);
console.log("Success", data);
});
}

And this is how you would use promises:

function saveThisUser(userDetails){
const userObj = new User(userDetails);
return user.save()
.then( data => {
console.log("Success", data);
})
.catch(err => {
console.log("Error", err);
});
}

There is no need to explain the first example.

See the 2nd code snippet. What do you do inside the .then() function?

.then( data => { 
console.log("Success", data)
})

Now using function blocks,

.then( function(data) {
console.log("Success", data);
})

Oh oh oh… You just passed a function inside .then() function. Similarly you pass a function inside .catch() function.

Now what do you call a function which is passed an an argument to another function?

Yes… You guessed it right… A Callback.

Wait wait wait… What just happened? Did you just use a callback inside Promise?

So when for using promises we need callbacks, then how come promises are better than callbacks?

This is the wrong concept being understood by lots and lots of people.

Both callbacks and promises are completely different concepts. One is not better than the other. Actually how can you actually compare both of them? It is like you want to compare an Apple and a Juicer. Which is better of these two?

So if someone asks you whether you can replace callbacks with promises, you know what to say…

If you ask me which is better callbacks or promises?

  1. CPU performance — Nope callbacks are better than promises.
  2. Code style — You can’t compare callbacks and promises as single units. Yes, Promise chains are a better coding style as compared to callback hells.

If you still believe I am wrong, write a Javascript code to print time upto seconds without using callbacks ;). My challenge…

--

--