When we work with web applications, there are many chances that we need to execute something asynchronously (like call 3rd party api, do some heavy stuff). To work with these asynchronous tasks, the first thing we think about is
callback
, but beside
callback
there is still one more technique to work with asynchronous is Promise. In this post, we will learn about the different between
Promise
and
Callback
.
What is asynchronous task
The main reason we need to use the asynchronous task is that we can’t determine exactly when we need to trigger something. Because it depends on something out of our control. For
What is callback
The main concept behind callback is we defined a method but we don’t execute it,but we will pass this method to something out of our control. Back to the example of a call to 3rd party API, we will do something like this “Hi API, when you finish your task, please help me to execute my function”. That is the way callback work. We will a callback function to someone else to trigger is instead of trigger it by ourselves.
Beside run on other context, callback can also carry value as input param which is pass from other context.
Callback example
See the Pen Callback by hieu (@phuchieuct93abc) on CodePen.light
But Callback has their own drawback
Callback helps us to handle asynchronous task but they have a big disadvantage is
callback hell
. So to understand what is it, let take an example: We want to call 3rd party API, after getting the response, we will wait 5 seconds to call another API, wait for respond 2 seconds, we will print out the result.
This is the code to implement that feature
See the Pen oOLpbK by hieu (@phuchieuct93abc) on CodePen.light
As you can observe that with a chain of
callback
which involve many callback functions trigger in sequentialy. Our code is blooded of a ton of indentation. Besides that, the most important one is when reading this callback hell, it’s very hard to describe the process: what happens first, what happens later, what happens right after another one.
Promise was born to solve this problem of callback
What is promise
Promise
in javascript has the same functionality as callback: both of them are used to handle the ansynchronous task. The main difference between them is
Promise
only to receive our callback function after the process is triggered. Compare to `
Let take a look what is callback:
See the Pen Promise by hieu (@phuchieuct93abc) on CodePen.light
Small comparison between callback vs Promise
See the Pen Promise vs callback by hieu (@phuchieuct93abc) on CodePen.light
If you’re interested in `Promise`, you could read on this blog https://frontend.cloudaccess.host/promise-in-javascript/ to figure more features of Promise
Summary
Callback Promise
has the same responsibility