user defined function with callback in nodejs

2019-04-05 10:38发布

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条回答
手持菜刀,她持情操
2楼-- · 2019-04-05 11:15

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
    }
});
查看更多
姐就是有狂的资本
3楼-- · 2019-04-05 11:26

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)
});
查看更多
登录 后发表回答