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
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.
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
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 only to receive our callback function after the process is triggered. Compare to `
Let take a look what is callback:
Small comparison between callback vs Promise
Promise has the same responsibility