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

man*_*ngh 11 asynchronous callback node.js

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

function login(username, password, function(err,result){
});
Run Code Online (Sandbox Code Playgroud)

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

jfr*_*d00 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);
    });
}
Run Code Online (Sandbox Code Playgroud)

并调用登录功能

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


Pla*_*ato 5

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

// 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)
});
Run Code Online (Sandbox Code Playgroud)