啊,第一次在node中学习异步js的乐趣:3
正如@mark_m所提到的,请求中的函数只有在处理请求之后才被调用。因此,不能从verifyuser()函数返回变量。verifyuser()在发送请求后立即返回,并在收到响应后调用request()中的函数。
理想情况下,您应该通过提供回调函数来遵循异步流:
//We'll define some function called 'callback'
function verifyUser(uname,pword, callback){
var options = {
url: 'CENSORED',
method: 'POST',
headers: headers,
form: {'Username':uname, 'Password':pword, 'Key':key}
}
request(options,callback);
// Here I've changed your inline callback function to the one passed to verifyUser as an argument.
}
// Then, your main code:
verifyuser("RobDeFlop","CENSORED", next);
function next(error,response,body){
if(!error && response.statusCode == 200){
//Do useful stuff with the body here.
}
})
}