What is callback?
callback is function which run one function after another. Node is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed.
or
a callback is a piece of executable code that is passed as an argument to other code. When the function is done with its work , it calls your callback function.
Callback Example:
fs.readFile(‘index.html’, function(err, data) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
res.write(data);
res.end();
});
What is callback hell?
callback hell nothing but nested callbacks.The code can get messy when there are several functions. This situation is called what is commonly known as a callback hell.
example:
firstFunction(args, function() {
secondFunction(args, function() {
thirdFunction(args, function() {
// And so on…
});
});
});
Solutions to callback hell
There are four solutions to callback hell:
- Write comments
- Split functions into smaller functions
- Using Promises
- Using Async/await
July 28, 2022 at 4:14 pm
I was pretty pleased to discover this great site. I want to to thank you for ones time due to this fantastic read!! I definitely appreciated every part of it and I have you book marked to look at new stuff on your web site.