11

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

2 Answers 2

23

Here's an example of the login function:

function login(username, password, callback) {
    var info = {user: username, pwd: password};
    request.post({url: "https://www.adomain.com/login", formData: info}, function(err, response) {
        callback(err, response);
    });
}

And calling the login function

login("bob", "wonderland", function(err, result)  {
    if (err) {
        // login did not succeed
    } else {
        // login successful
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

new to JS, shouldn't it be login(username, password, callback { ?
@Suhaib - Not exactly, but there was a mistake in the first one which I fixed.
6

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)
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.