Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user defined function with callback in nodejs

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

like image 409
manpreetSingh Avatar asked Apr 04 '15 14:04

manpreetSingh


People also ask

How do you create a callback function in 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.

Is callback a keyword in NodeJS?

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.

Why do we use callback functions extensively in NodeJS?

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.

How many callback functions can ever be executing at any time?

As long as the callback code is purely sync than no two functions can execute parallel.


1 Answers

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)
});
like image 115
Plato Avatar answered Oct 21 '22 12:10

Plato