Understanding the concepts of Callbacks and Promises can be rather confusing sometimes, especially when you are hardly a hardcore Javascript developer or new to it. In another case, If you are working as Node.js developer or want to start a career as one 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.

Javascript is a synchronous language, it is single-threaded, this means that each instruction in a program is executed step by step, each blocking the processor until it completes execution. Asynchronous on the other hand does not block the processor but execute the tasks in parallel or use a mechanism that makes it look like they work in parallel. To achieve parallelism most programming languages use the concept of threads. The main thread spawns other threads to do some work so that the main program is not blocked.

To understand Callbacks & Promises we must learn to appreciate their usefulness in carrying out asynchronous operations in Javascript.

There are different mechanisms that help you deal with async tasks, but we’ll be looking into two of the most popular ones, Callbacks, and Promises.

Callbacks

So in simple parlance, A callback is a function that we call inside another function. It may or may not be executed asynchronously. Normally callback runs after the parent function completes its operation.

Let’s see an example below


// execute
function getData(data, callback) {
  setTimeout(()=> {
    console.log("reading from the database...");
    callback({data: data});
  }, 2000)
}

// display
getData(5, function(data){
  console.log(data);
});

On the execute block, getData() is a function that simulates getting data from a database, the first argument is the data and the second argument would be the callback which we want to run when we get back that data. For quick simulation, we are going to be using the timeout function which will run after a certain amount of time. On the display, the callback is the function that is executed after the data, which is 5, in this case, is fetched and the set time has elapsed in this case.

Here callback is executed asynchronously.

Promises

Promises are alternatives to a callback. It is basically an object which takes a callback and executes it asynchronously. A promise can either resolve (be successful) or reject (some error occurred), pending: still executing.

A promise is considered easier to use and maintain than callbacks, mostly because the syntax is much simpler.


const promise = new Promise((resolve, reject) => {
    // perform async operation here

    if () {
        // everything turned out fine
        resolve("response worked!");
    }
    else {
        reject(new Error("something went wrong"));
    }
});

promise.then((result) => {
    console.log(result); // "response worked!"
}).catch((err) => {
    console.log(err); // "something went wrong"
});

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

The .catch() block helps you handle any error that occurs in the .then() chain.

Also, you may observe that 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.

Conclusion

There’s more to asynchronous operations in Javascript and we just scratched the surface, but it’s good practice to understand the concepts of Callbacks and Promises as it will form a good foundation for dealing with asynchronous operations especially when making API requests and event handling.

Happy coding!!!

Henry Ugochukwu
Author

I am passionate about building the future for sustainable businesses in Africa leveraging technology.

Write A Comment