如何从async fetch函数获取返回数据而非Pending Promise?
解决async函数返回
Promise {<pending>}的问题 你遇到的问题本质是async函数的返回值本身就是Promise对象——不管内部用了多少await,调用它时都会立即返回一个处于pending状态的Promise,直到内部异步操作完成,Promise才会变成resolved状态并携带实际结果。
两种获取实际返回值的方法
方法1:在async函数内用await调用
await只能在async函数中使用,所以你需要把调用逻辑放到一个async函数里:
async function fetchData() { const status = await getapi(api_url, headers, post); console.log(status); // 这里就能拿到{status: 1, result: 1} } fetchData();
方法2:用.then()处理Promise
如果不想额外套async函数,直接用Promise的.then()方法获取结果:
getapi(api_url, headers, post).then(status => { console.log(status); // 同样能拿到实际数据 });
优化你的getapi函数
原函数里的if (response)判断意义不大——只要fetch没触发网络错误,response就会存在,但HTTP状态码4xx/5xx这类错误不会触发fetch的reject,建议加上response.ok判断确保请求成功:
async function getapi(u, h, p) { const response = await fetch(u, { method: "POST", headers: h, body: JSON.stringify(p) }); // 判断HTTP请求是否成功(状态码200-299) if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); return data; }
还可以通过.catch()或try/catch捕获错误,让函数更健壮:
// await方式捕获错误 async function fetchData() { try { const status = await getapi(api_url, headers, post); console.log(status); } catch (error) { console.error('获取数据失败:', error); } } fetchData(); // .then()方式捕获错误 getapi(api_url, headers, post) .then(status => console.log(status)) .catch(error => console.error('获取数据失败:', error));
内容的提问来源于stack exchange,提问作者Davidicusrex
相关产品推荐
相关产品推荐

