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
user defined function with callback in nodejs
提问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)
});

