Hey, I am here to drop off my car for an oil change awesome it’ll take about an hour and what number can we call you at when we’re done awesome yeah you can call me back at 1111111 Now that’s the callback.
According to Doc. - Callbacks are a special type of function that pass as an argument to another function
Callbacks help us make asynchronous calls.
Syntax of a callback in Node:
function function_Name(argument,callback);
Callback as an arrow function
function function_Name(argument,(callback_argument)=>{
//callback..
});
Example with arrow Function.
setTimeout(()=>{
console.log("Callback as Arrow Function");
},1000);
Output
Asynchronous Programming
Asynchronous programming is an approach to running multiple programs at a time without blocking the other parts of the code. Node js makes heavy use of callbacks for asynchronous programming APIs are written in such a way that they support callbacks. There is no need to block other blocks of the code to print the result.
For Example
//Blocking code
// fs.readfileSyn() method
const fs = require('fs');
const data = fs.readFileSync('./input.txt',{ encoding: 'utf8', flag: 'r'});
console.log(data);
console.log("Program End");
Output
But this way our code holds up the execution of the rest of the program until it finishes its execution and prints the result.
as you can see in the above code console.log("Program End"); can not be executed until the above readFileSyn function not executed
Now with Callback
//Non blocking
const fs = require('fs');
fs.readFile('./input.txt',{ encoding: 'utf8', flag: 'r' },(err,data)=>{
if(err)return console.error(err);
console.log(data);
})
console.log('Program end');
Output
In the above example, the program does not wait for the reading file and proceeds to print the "program end" and at the same time, the program without blocking continues reading the file
Thank you for reading my content. Be sure to follow and comment on what you want me to write about next :)