在Node.js中使用回调的用户定义函数

11

有人可以给我一个例子吗?例子中我们创建一个包含回调函数的特定函数。

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

我应该把登录功能和回调函数的代码放在哪里?
附注:我是nodejs的新手。

2个回答

23

这是登录功能的示例:

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

刚接触JS,应该是 login(username, password, callback { 吧? - Suhaib
@Suhaib - 不完全是,但第一个有一个错误,我已经修复了。 - jfriend00

6

这个问题不太好,但是无论如何你已经混淆了调用和定义异步函数:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接