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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29447451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:36:51  来源:igfitidea点击:

user defined function with callback in nodejs

node.jsasynchronouscallback

提问by manpreetSingh

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

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

回答by jfriend00

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

回答by Plato

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