所以你可以做的是你可以将异步函数转换成一个promise,它会等待执行完成。错误处理的执行如下。
export const LoginScreen = async () => {
const [formValues, handleInputChange] = useForm({
email: "",
password: "",
});
const start = function () {
// converting into a async promise
return new Promise(async (resolve, reject) => {
try {
const resp = await fetch("http://localhost:3003/login", {
method: "POST",
body: JSON.stringify({
email: formValues.email,
password: formValues.password,
}),
headers: {
"Content-Type": "application/json",
},
});
const data = await resp.json();
// resolving on success
resolve(data);
} catch (error) {
// rejecting on failures
reject(error);
}
});
};
// Now this will await the start function to be completed.
const t = await start();
console.log(t);
const handleSubmit = (e) => {
e.preventDefault();
};
};
解释:由于我们已经在异步函数内部等待,JS 倾向于跳过它,除非它是一个需要明确解决的承诺。因此,现在将您的函数转换为 Promise,我们可以等待它被解析。
我为 NODE 做了一个简单的工作示例,
const LoginScreen = async () => {
const start = function () {
// converting into a async promise
return new Promise(async (resolve, reject) => {
try {
setTimeout(() => {
return("Hello");
}, 3000);
} catch (error) {
// rejecting on failures
reject(error);
}
});
};
const t = await start();
console.log(t);
const handleSubmit = (e) => {
e.preventDefault();
};
};
LoginScreen();
如果你看到了,该函数现在会等待 3 秒,然后在启动函数解析后将数据保存在 t 中
沙盒链接的代码更新
import { useForm } from "./useForm";
export const LoginScreen = () => {
const [formValues, handleInputChange] = useForm({
email: "",
password: ""
});
// const formValues = { email: "", password: "" };
const start = function () {
// -------------- important -------------------
return new Promise(async (resolve, reject) => {
// -------------- important -------------------
const resp = await fetch("http://localhost:3003/login", {
method: "POST",
body: JSON.stringify({
email: formValues.email,
password: formValues.password
}),
headers: {
"Content-Type": "application/json"
}
});
const data = await resp.json();
resolve(data);
});
};
const handleSubmit = async (e) => {
// -------------- important -------------------
console.log("Submitting");
e.preventDefault();
const t = await start();
console.log(t);
// -------------- important -------------------
};
return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<input
autoComplete="off"
type="email"
placeholder="Enter email"
name="email"
value={formValues.email}
onChange={handleInputChange}
required
/>
<input
autoComplete="off"
type="password"
placeholder="Enter password"
name="password"
value={formValues.password}
onChange={handleInputChange}
required
/>
<button type="submit">Login</button>
</form>
</div>
);
};
这是有效的,我已经评论了一些部分以加快开发,您取消评论并继续前进。现在它们应该可以工作了。
现在您肯定会将值分配给“t”。确保你做了一些错误处理,然后你可以将此令牌传递给主函数,你可以使用回调方法,也可以使用全局上下文并以更好的方式管理状态。
如果仍然失败,请告诉我,我们可以找到更好的解决方案。
编码愉快。