Skip to main content

Difference between callback functions and promises in javascript

If you have ever worked with JavaScript you might have the experience that it is a quite confusing language to understand at first. This is because  in JavaScript there are many ways to do the same thing, and also unlike most other programming languages, if you do a small mistake in JavaScript instead of giving any errors, the program would behave in a totally different way than what you expect. Therefore, without understanding the basic concepts of JavaScript, it's quite difficult to work with it. In this post I'll be explaining about callback functions and promises, what they are used for and the difference between the two methods. Actually callback functions and promises are 2 different ways of doing the same thing.

By default JavaScript is an asynchronous programming language. Which means that JavaScript does not execute instructions line after the other as in many programming languages. Whenever JavaScript come across an operation that takes relatively a long time, typically an IO operation, it executes this in the background and jumps to the next line of code. This is typically visible if you try to read data from a file and console the content of the file. If you do this in the normal way, program will probably print undefined in the console. This is because by the time JavaScript executes the console.log() function , the file read operation has not yet completed its execution.
Try out the following piece of code to experience this behavior.


Note that test.txt is a text file inside the folder in which the program code is saved.

The above behavior can be simply avoided by reading the file synchronously, as in the below code fragment.


Though the above code solves our problem, it is not a good way of handling asynchronous operations in JavaScript. Why? Because it decreases the efficiency of the code execution.

So, how can we handle asynchronous operations in a synchronous ? The answer is callback functions and promises. First, lets look how we can use call back functions to get rid of our problem.

Callback functions 

A callback function is a function that is passed as an argument to another function. Once the first function finish its execution, the function that was passed as the argument will be executed. Below code is an example of a callback function.


As you can see from the above code callback functions have less readability, and is quite difficult to understand. This can be worse in situations where we want to chain a set of asynchronous operations one after the other. How can we improve readability , and do the same thing a more meaningful way?

Promises

Promises are used to express callback functions in a more meaningful manner, which is easier to read and understand. A Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation. The significant difference between using callback functions and promises can be seen when we want to chain a set of events. An example of using promises is provided below.

const fs = require('fs');
const fp = __dirname+ "/test.txt";

//PROMISESlet fileContent;
var readFile1 = function () {
    //returning the promise object    
return new Promise(function (resolve, reject){//resolve is if the process is success,
   fs.readFile(fp, function (err, data) {    // reject if the process fail
            resolve(data);
        });
    })
}
function readFile2() {
    const promise = new Promise((resolve, reject) => {
        fs.readFile('test2.txt', (err, data ) =>{
            if(err){
                return reject(err);
            }
            return resolve(data);
        })
    })
    return promise;
}
//if promise is successful then execute this functionreadFile1().then(function(data){
    fileContent = data.toString();
    return readFile2();
}).then(function (data) {
    fileContent = fileContent.concat('\n').concat(data);
    return fileContent;
}).then(function (content) {
    console.log(content);
});

Comments

Popular posts from this blog

A comparison between Node and Express

If you are programmer who have worked a long time with JavaScript you might know that , earlier JavaScript was just a scripting language used in the client side. However now the story is different. With many libraries like Node js and Express js being added to the JavaScript family JavaScript have evolved beyond, just being a scripting language in the client side. With these new libraries being added, now it is possible to build entire sites on JavaScript, extending it from front to back-end seamlessly. So what is Node and Express? Let's  clear this out step by step! What is Node js? Node js is an open source JavaScript runtime environment that executes JavaScript code server side. Node enables developers to use JavaScript for server side scripting. Node uses an event driven, non-blocking I/O model that makes it light weight and efficient. Because of this model Node js is particularly useful in web application that have many input/output operations and for real time web appli...

How to use Git and GitHub from Netbeans

As some of  you all might know Git is a popular version control tool for tracking changes in computer files and managing work among several people. GitHub is a web-based Git or version control repository and Internet hosting service. GitHub helps you to host and review code, manage projects and build software alongside millions of other developers. The whole scenario of using Git and GitHub is based on creating a repository where you can save your code. Git allows you to create a local repository on your own PC, whereas GitHub enable you to push/copy the content of your local repository to a global(remote) repository where other developers can access your code. This blog is about how to configure and use Git and GitHub from the NetBeans IDE. 1. Install Git on your PC.  You can download it from the following link . URL :  Download Git 2.Create a GitHub account.  If you already have one just sign in to that account. Go to GitHub      3...