Wie erhalte ich den Abrufstatus korrekt?
P粉124070451
P粉124070451 2023-09-08 18:25:24
0
1
466

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 { : "fulfilled", : 201 }' }

P粉124070451
P粉124070451

Antworte allen (1)
P粉509383150

如果您希望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; }
    Neueste Downloads
    Mehr>
    Web-Effekte
    Quellcode der Website
    Website-Materialien
    Frontend-Vorlage
    Über uns Haftungsausschluss Sitemap
    Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!