If you are a web developer starting out you have most certainly heard of these terms. Before we get to compare these concepts let’s talk about why would we need these at the first place.
Let’s say we are writing a front end application that fetches
apples from a server. However, let’s assume the response we get back is delayed by 2 seconds or so. We mimic this scenario with the code below.
So this will not work because out variable myApple is assigned and executed right away.
getApple function however tries to set the object in 2 seconds. So we will not get the expected output in a real world scenario.
To deal with such situations callbacks were introduced. The code below solves this problem using callbacks
we now pass a callback function to
this callback function is received as a normal function argument and executed once the timer completes.
This idea of callbacks were very popular and it is still getting used a lot.
However, when building more complex applications we find ourselves in a callback loop
also know as the callback hell. Consider this example for instance.
Nesting callbacks can make applications very hard to debug and maintain clean code.
To solve these problems promises were introduced. Let’s take a look at the same example with promises.