Saturday, September 21, 2024
Google search engine
HomeLanguagesJavascriptPromise vs Callback in JavaScript

Promise vs Callback in JavaScript

In this article, we will cover Promises, callbacks, and the difference between them.

What are Promises in JS?

To manage asynchronous actions in JavaScript, promises are used. It is an assurance that something will be done. The promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred.

 

A Promise has four states: 

  • fulfilled: Action related to the promise succeeded
  • rejected: Action related to the promise failed
  • pending: Promise is still pending i.e. not fulfilled or rejected yet
  • settled: Promise has fulfilled or rejected

Syntax:

var promise = new Promise(function(resolve, reject){
    // do something
});

A promise can be created using Promise constructor.

Parameters:

  • Promise constructor takes only one argument which is a callback function (and that callback function is also referred as an anonymous function too).
  • Callback function takes two arguments, resolve and reject
  • Perform operations inside the callback function and if everything went well then call resolve.
  • If desired operations do not go well then call reject.

Example:

Javascript




var promise = new Promise(function(resolve, reject) {
const x = "neveropen";
const y = "neveropen"
if(x === y) {
    resolve();
} else {
    reject();
}
});
      
promise.
    then(function () {
        console.log('Success, You are a GEEK');
    }).
    catch(function () {
        console.log('Some error has occurred');
    });


Output:

Success, You are a GEEK

Benefits of Promises:

  • Improves Code Readability
  • Better handling of asynchronous operations
  • Better flow of control definition in asynchronous logic
  • Better Error Handling

What is Callback in JS ?

Callbacks are a great approach to dealing with something once another task has been finished. Here, “something” refers to the execution of a function. Callbacks can be utilized if we wish to run a function immediately following the return of another function.

The type of JavaScript function is objects. They may therefore be supplied as an argument to any other function when calling them, just like any other objects (Strings, Arrays, etc.).

JavaScript code to show the working of the callback:

Javascript




// The add() function is called with arguments a, b
// and callback, callback will be executed just
// after ending of add() function
function add(a, b , callback){
    console.log(`The sum of ${a} and ${b} is ${a+b}`);
    callback();
}
  
// The disp() function is called just
// after the ending of add() function
function disp(){
    console.log('This must be printed after addition');
}
  
// Calling add() function
add(5,6,disp)


Output:

The sum of 5 and 6 is 11.
This must be printed after addition

Explanation:

Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers.

As a result, the add() is invoked with 1, 2, and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the additional output.

The benefit of Callback:

  • You can run another function call after waiting for the outcome of a prior function call.
  • You can call the parent function from the child function and can also pass data from child to parent.

Promise vs Callback in JavaScript

  JavaScript Callback JavaScript Promise
Syntax The syntax is difficult to understand. The syntax is user-friendly and easy to read because of then and catch.
Error handling Error handling may be hard to manage. Error handling is easier to manage using catch block.
Callback hell It may create callback hell. It resolves callback hell.

RELATED ARTICLES

Most Popular

Recent Comments