DEV Community

Cover image for Understanding JavaScript Promises and Callbacks
Jenish Dabhi
Jenish Dabhi

Posted on

Understanding JavaScript Promises and Callbacks

As JavaScript programmers, we frequently deal with asynchronous tasks in our applications. Managing these tasks can be challenging, but JavaScript Promises provides a neat and effective approach to handling them.

What are JavaScript Promises?
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.

Promises are similar to real-life commitments we make in our daily lives. For example, consider a scenario where you make a promise to your friends that you will take them to a party next weekend. However, in reality, you’re uncertain whether you’ll have time on the weekend or not. This means that you might not be able to fulfill that promise.

So there may be three chances:

  • Pending: You don't know whether you will have time or not.
  • Fulfilled: You gave them a party.
  • Rejected: You didn't give a party to them.

A Promise starts with the pending state, then moves to either the fulfilled or rejected state after the asynchronous operation is completed.

See below example :

function makePromise(partyPromise) {
 return new Promise(function (resolve, reject) {
    setTimeout(() => {
        if (partyPromise) {
            resolve("I given party to friends");
        } else {
            reject("I am not given party to friends");
        }
    }, 5 * 1000);
});
}
let partyPromise = makePromise(true);
partyPromise
    .then(success => console.log(success))
    .catch(reason => console.log(reason))
    .finally(() => console.log("Friends are ready for party !"))
Enter fullscreen mode Exit fullscreen mode

The Benefits of Promises:

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

What are Callback Functions?

A callback function in JavaScript is a function that is passed as an argument to another function and is executed inside the outer function to complete some kind of routine or action. Callback functions help us manage asynchronous operations, making our code more organized and easier to understand.

Basic Syntax of a JavaScript Callback Function

function greet(name, callback) {
  console.log(`Hello, ${name}!`);
  callback();
}

greet('Jenish', function () {
  console.log('This is a callback function');
});
Enter fullscreen mode Exit fullscreen mode

In the example above, we define a greet function that accepts two arguments: a name and a callback function. After logging a greeting message, the greet function executes the callback function.

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

Callback vs Promises

  • A callback function is passed as an argument to another function, whereas a promise is an object that you interact with using its methods, such as then and catch.
  • Promises are chainable, meaning that multiple operations can be queued up and executed in order, unlike callbacks which would require callback hell.

Thank you for reading.
Happy coding!

Top comments (0)