【发布时间】:2015-06-09 10:40:08
【问题描述】:
谁能给我一个例子,我们正在创建一个特定的函数,它也有一个回调函数?
function login(username, password, function(err,result){
});
登录函数和回调函数的代码应该放在哪里?
ps:我是nodejs的新手
【问题讨论】:
标签: node.js asynchronous callback
谁能给我一个例子,我们正在创建一个特定的函数,它也有一个回调函数?
function login(username, password, function(err,result){
});
登录函数和回调函数的代码应该放在哪里?
ps:我是nodejs的新手
【问题讨论】:
标签: node.js asynchronous callback
这里是登录功能的一个例子:
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
}
});
【讨论】:
login(username, password, callback {吗?
不好的问题,但 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)
});
【讨论】: