我在我的 api 中执行提取,它返回 201 状态,但是当我尝试在变量中接收它时,状态变得很奇怪。
useEffect(() => {
async function Verify (test) {
await fetch("/api/test", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({test: test}),
}).then((response) => {
res = response.status;
console.log(res); //thats print '201'
return res;
});
}
const status = Verify(test);
console.log(status); //thats print 'Promise { <state>: "fulfilled", <value>: 201 }'
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您希望
status等于Verify的结果,您需要await它。此外,我建议重构您的代码以在各处使用
await来简化流程。尝试这样的事情:async function Verify (test) { const res = await fetch('/api/test', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify( { test } ), }); if (!res.ok) { throw new Error('Not-ok response from server'); } return res; }