can anyone give me an example in which we are creating a particular function, which is also having a callback function ?
function login(username, password, function(err,result){
});
where should I put the code of the login function and callback function?
p.s.: I am new to nodejs
For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter.
For your top function, callback is the name of the third argument; it expects this to be a function, and it is provided when the method is called. It's not a language keyword - if you did a "find/replace all" of the word "callback" with "batmanvsuperman", it would still work.
In node. js, we basically use callbacks for handling asynchronous operations like – making any I/O request, database operations or calling an API to fetch some data. Callback allows our code to not get blocked when a process is taking a long time.
As long as the callback code is purely sync than no two functions can execute parallel.
bad question but w/e
you have mixed up invoking and defining an asynchronous function:
// define async function:
function login(username, password, callback){
console.log('I will be logged second');
// Another async call nested inside. A common pattern:
setTimeout(function(){
console.log('I will be logged third');
callback(null, {});
}, 1000);
};
// invoke async function:
console.log('I will be logged first');
login(username, password, function(err,result){
console.log('I will be logged fourth');
console.log('The user is', result)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With