我现在正在使用request
节点包连接到API,制作一个节点应用程序。但是,当我发出API请求时,确定username
和password
的有效性的函数未按预期返回true
。
到目前为止,这是我的代码:
const request = require("request")
const API_URL = <the_api_url>
const isValidLogin = (username, password) => {
let success = false;
let options = {
url: API_URL,
method: 'GET',
auth: {
user: username,
pass: password
}
}
request(options, (error, response, body) => {
console.log(response.statusCode);
if (error) {
console.log(error)
}
if (response.statusCode == 200) {
success = true;
}
else {
success = false
}
})
console.log(success)
return success;
}
当我将无效的username
和password
传递到isValidLogin()
时,它正确地返回false。我确实注意到response.statusCode
是200
,这意味着success
是true
,但是它没有按预期工作。
答案 0 :(得分:2)
request()
函数是异步的,这基本上意味着request()
函数调用的结果将在将来返回。对于这种request()
方法,将来会通过回调(即您正在测试statusCode
的地方)返回结果。
要基于对success
的调用正确返回request()
结果,您需要执行以下两项操作之一:
isValidLogin()
定义为异步函数/返回将来会解决的承诺: /* Add asnyc means this function is now asynchronous */
const isValidLogin = async (username, password) => {
let success = false;
let options = {
url: API_URL,
method: 'GET',
auth: {
user: username,
pass: password
}
}
/* return the result of the request when the request
has completed */
return await (new Promise(resolve, reject) => {
request(options, (error, response, body) => {
if (response.statusCode == 200) {
resolve(true);
}
else {
resolve(false);
}
});
});
}
/* Requires the surrounding function to be async */
const success = await isValidLogin('john', 'password');
isValidLogin
完成后将回调传递给success
,并以request()
结果进行调用:
/* onComplete is the added callback that is fired when request() completes */
const isValidLogin = (username, password, onComplete) => {
let success = false;
let options = {
url: API_URL,
method: 'GET',
auth: {
user: username,
pass: password
}
}
request(options, (error, response, body) => {
console.log(response.statusCode);
if (error) {
console.log(error)
}
if (response.statusCode == 200) {
onComplete(true);
}
else {
onComplete(false)
}
});
}
/* Usage example */
isValidLogin('john', 'password', (success) => {
console.log(`the request completed in the future
and the result was ${success}`)
})