What is the Callback function in node js?
In this chapter, you will learn What is callback function in node js.
Callback functions help us in the situation where, the function may accept some params and it may return a result after some time, not immediately. For example, when we call external third API services, these APIs may take some time to return the data. For handling this kind of situation the javascript provide the callback function approach to manage this problem easily.
Consider the below example, where a company generates an employee report at the end of the month. For generating a report it may take some time, so registering the callback. Once the generating the report has been finished then the data will be returned back.
Create a file: server.js and put the below
Run the command:
node server
const employeeReport = (name, callback) => { setTimeout(()=>{ const report = { name:name, workingDays:22, leaves:1 }; callback(report); },2000); } employeeReport('John', (report)=>{ console.log('Empoloyee report'); console.log(report); }); //output Employee report { name: 'John', workingDays: 22, leaves: 1 }
One thought on “What is the Callback function in node js?”
Comments are closed.