JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print How to Print a Page Using JavaScript Textbox events in JavaScript How to find the largest number contained in a JavaScript Array?

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on the server side because it comes with a runtime environment (Node.js). Callbacks and callback hell are two topics we'll talk about in this article. Start with JavaScript's synchronous and asynchronous implementations to understand what the callback hell is. The result is returned as soon as the browser is able to in Synchronous JavaScript when the code is executed. Because it is single-threaded, only one operation can take place at once. Therefore, while an operation is running, all other processes are suspended. AJAX is necessary for several JavaScript functions because their responses aren't always immediate. It takes some time. Therefore the subsequent operation cannot begin right away. It must wait for the background function to complete. The callbacks must be asynchronous in these situations. A callback is a function that is supplied as an argument to a different function, which, depending on the outcome, will then execute the callback. Carry on reading to understand more about this.

What is a callback?

Callbacks are an excellent approach to address something once another task has been done. Here, "something" refers to the execution of a function. Callbacks can be utilised if we wish to run a function immediately following the return of another function. Callbacks are generally utilised when managing asynchronous processes, such as registering event listeners, sending an API request to Google Maps, retrieving/writing data from/into a file, and other related tasks. Callbacks are used in all of the aforementioned operations. In this manner, the callbacks are utilised to handle the data or error from the asynchronous action once it is returned to our code.

See the following code to understand more about the callback.

Example 1:

function addition(a, b , callback){
console.log(`The sum of ${a} and ${b} is ${a+b}.`);
callback();
}
function display(){
console.log('This must be printed after addition');
}
	
addition(2,3,display);	

Output:

Callback and Callback Hell in JavaScript

Explanation:

The two functions are display and addition (a, b, callback) (). The display() method is called with the addition() function, which is provided as the third parameter to the add function along with two numbers. As a result, the callback display(), along with arguments 1, 2, and addition(), is executed. The callback function is activated as soon as the addition of the two numbers is printed by addition(). Therefore, whatever is contained in the display() appears as the output.

Example 2:

function sub(a, b , callback){
console.log(`The subtraction of ${a} and ${b} is ${a-b}.` );
callback();
}
sub(5,6,function display(){
console.log('This must be printed after subtraction.');
});

Output:

Callback and Callback Hell in JavaScript

Example 3:

const mainFunction = (callback) => {
	setTimeout(() => {
		callback([2, 3, 4]);
	}, 2000)
}
const add = (array) => {
	let sum = 0;
	for(let i of array) {
		sum += i;
	}
	console.log(sum);
}
mainFunction(add);

Output:

Callback and Callback Hell in JavaScript

Explanation:

To simulate certain I/O operations or a request call, setTimeout has been utilised in the mainFunction in this case. The callback function that was supplied is utilised to add up the array's elements. The array's sum, which is nine, is printed after two seconds.

What is callback hell?

This is a significant problem brought on by complicated callback nesting in the code. Every callback in this situation accepts an argument that is the outcome of earlier callbacks. The code structure resembles a pyramid in this way, making it challenging to comprehend and maintain. Additionally, if one function has a bug, it affects the entire system.

How to handle callback hell?

  1. Any asynchronous function will return an object called a promise, to which callback methods can be added depending on the output of the prior function.
  2. As a result, these promises are added to the event queue so that they won't obstruct running JS code. The event queue also completes its tasks once the results are returned.
  3. JavaScript offers a simple way out of callback hell. The event queue and promises are used for this.
  4. Promises can invoke async callbacks using the. then() method. The order is likewise rigidly maintained, and we are free to chain as many callbacks as we like.
  5. The. fetch() method is used by promises to retrieve objects from the network. When a block fails, it also employs the. catch() method to handle any exceptions.