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
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.
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.
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
Post a Comment