首页  >  问答  >  正文

如何正确获取 fetch 的状态?

我在我的 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 }'

}

P粉124070451P粉124070451407 天前541

全部回复(1)我来回复

  • P粉509383150

    P粉5093831502023-09-09 09:45:31

    如果您希望status等于Verify的结果,您需要await它。

    const status = await Verify(test);

    此外,我建议重构您的代码以在各处使用 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;
    }

    回复
    0
  • 取消回复