用户定义的函数,在nodejs中有回调

时间:2015-04-04 14:16:47

标签: node.js asynchronous callback

任何人都可以给我一个例子,我们正在创建一个特殊的函数,它也有一个回调函数吗?

function login(username, password, function(err,result){
});

我应该在哪里放置登录功能和回调函数的代码?
p.s。:我是nodejs的新手

2 个答案:

答案 0 :(得分:22)

以下是登录功能的示例:

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

并调用登录功能

login("bob", "wonderland", function(err, result)  {
    if (err) {
        // login did not succeed
    } else {
        // login successful
    }
});

答案 1 :(得分:5)

糟糕的问题,但是w / e
你混淆了调用和定义异步函数:

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