Skip to content
Advertisement

Aren’t promises just callbacks?

I’ve been developing JavaScript for a few years and I don’t understand the fuss about promises at all.

It seems like all I do is change:

JavaScript

Which I could use a library like async for anyway, with something like:

JavaScript

Which is more code and less readable. I didn’t gain anything here, it’s not suddenly magically ‘flat’ either. Not to mention having to convert things to promises.

So, what’s the big fuss about promises here?

Advertisement

Answer

Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you get little benefit. But if you write them the way they are meant to be used, you can write asynchronous code in a way that resembles synchronous code and is much more easy to follow:

JavaScript

Certainly, not much less code, but much more readable.

But this is not the end. Let’s discover the true benefits: What if you wanted to check for any error in any of the steps? It would be hell to do it with callbacks, but with promises, is a piece of cake:

JavaScript

Pretty much the same as a try { ... } catch block.

Even better:

JavaScript

And even better: What if those 3 calls to api, api2, api3 could run simultaneously (e.g. if they were AJAX calls) but you needed to wait for the three? Without promises, you should have to create some sort of counter. With promises, using the ES6 notation, is another piece of cake and pretty neat:

JavaScript

Hope you see Promises in a new light now.

Advertisement