我正在尝试向我的 React 应用程序添加登录功能,并且我有一个函数向 API 发送 post 请求,该 API 返回令牌。我在登录功能中使用了 async/await。这是我的代码:
Login.js
import axios from "axios";
const baseUrl = "/api/login";
const login = async (user) => {
const res = await axios.post(baseUrl, user);
console.log(res.data) //here it logs the data but the return value is unresolved promise.
return res.data;
};
export { login };
使用该功能的部分是:
const handleSubmit = async (e) => {
e.preventDefault();
let user = await login({
username,
password,
});
setUser(user); //Adding the user to component state.
}
我不知道为什么只有在 post 请求完成后才返回 res.data 时,我必须使用 await 调用登录函数:
const res = await axios.post(baseUrl, user);
如果没有等待,登录函数只会返回一个未解析的承诺。