Heim  >  Fragen und Antworten  >  Hauptteil

Wie erhalte ich den Abrufstatus korrekt?

Ich führe einen Abruf in meiner API durch und sie gibt den Status 201 zurück, aber wenn ich versuche, ihn in einer Variablen zu empfangen, wird der Status seltsam.

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 Tage vor540

Antworte allen(1)Ich werde antworten

  • 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;
    }

    Antwort
    0
  • StornierenAntwort