Site icon Learn Web Development & Programming, Artificial Intelligence, WordPress, Shopify Articles

Basic Difference Between Callback and Promise

callback-vs-promise

If you are working as Node js Developer or want to start a career as Node js Developer then you should know the difference between callback and promise. In this article, I will explain to you the basic difference between callback and promise in an easy way.

In Javascript, you have two main methods to handle asynchronous tasks – 1. Callback and 2. Promise. For very long time, synchronizing asynchronous tasks in JavaScript was serious issue. This difficulty affects back-end developers using Node.js as well as front-end developers using any JavaScript framework. Asynchronous programming is part of our daily work, but the challenge is often taken lightly and not considered at the right time.

Now we will learn the basic definition of callback and promise with an example:

Callback:

A Callback is a function that we call inside another function. A callback may or may not performed asynchronously. Normally callback runs after the parent function completes its operation.

Here calculate() is a function. We are passing it as a callback to function display(). Function display() may or may not execute it asynchronously. Here callback is executed asynchronously.

Promise:

A Promise is an object which takes a callback and executes it asynchronously. A promise is considered easier to use and to maintain than callbacks.

As we can see, then() takes two arguments, one for success, one for failure (or fulfill and reject, in promises-speak).

A promise did not remove the use of callbacks, but it made the chaining of functions straightforward and simplified the code, making it much easier to read.

If you will compare the Promise code, it is much more readable then Callback function code.

Exit mobile version