我正在向 API 服务器发出请求来验证用户身份,这不是问题。问题是我不知道为什么我的异步函数不返回任何内容,并且我收到错误,因为我想要从此函数获取的数据未定义。
不要担心错误管理是否丑陋,一般来说我可以做得更好,解决这个问题后我会这样做。
Utils.js 类
async Auth(username, password) {
const body = {
username: username,
password: password
};
let req_uuid = '';
await this.setupUUID()
.then((uuid) => {
req_uuid = uuid;
})
.catch((e) => {
console.error(e);
});
let jwtData = {
"req_uuid": req_uuid,
"origin": "launcher",
"scope": "ec_auth"
};
console.log(req_uuid);
let jwtToken = jwt.sign(jwtData, 'lulz');
await fetch('http://api.myapi.cc/authenticate', {
method: 'POST',
headers: { "Content-Type": "application/json", "identify": jwtToken },
body: JSON.stringify(body),
})
.then((res) => {
// console.log(res);
// If the status is OK (200) get the json data of the response containing the token and return it
if (res.status == 200) {
res.json()
.then((data) => {
return Promise.resolve(data);
});
// If the response status is 401 return an error containing the error code and message
} else if (res.status == 401) {
res.json()
.then((data) => {
console.log(data.message);
});
throw ({ code: 401, msg: 'Wrong username or password' });
// If the response status is 400 (Bad Request) display unknown error message (this sould never happen)
} else if (res.status == 400) {
throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
}
})
// If there's an error with the fetch request itself then display a dialog box with the error message
.catch((error) => {
// If it's a "normal" error, so it has a code, don't put inside a new error object
if(error.code) {
return Promise.reject(error);
} else {
return Promise.reject({ code: 'critical', msg: error });
}
});
}
Main.js 文件
utils.Auth('user123', 'admin')
.then((res) => {
console.log(res); // undefined
});
最佳答案
您的异步函数必须返回最后一个 promise :
return fetch('http://api.myapi.cc/authenticate', ...);
或者等待结果并返回:
var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;
请注意,您不需要将 Promise 语法 (.then) 与 wait 混合使用。你可以,但你不需要,而且可能也不应该。
这两个函数执行完全相同的操作:
function a() {
return functionReturningPromise().then(function (result) {
return result + 1;
});
}
async function b() {
return (await functionReturningPromise()) + 1;
}
关于javascript - 异步函数返回未定义而不是数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55985343/