You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

async await函数调用返回Promise pending而非结果该如何处理

问题原因
  1. 所有async函数的返回值本身就必然是Promise类型,你同步调用函数时,异步请求还未执行完成,拿到的自然是处于pending状态的Promise对象,不可能直接返回接口数据。
  2. 你当前编写的GetProfile函数内部逻辑存在缺陷,无法向外传递接口返回数据:
  • resp.json()本身也是一个异步Promise,你仅在回调里打印了该对象,没有将其返回给外层
  • 混用async/await和.then的写法逻辑混乱,整个函数没有显式返回接口解析后的结果,即使异步执行完成,最终Promise的兑现值也是undefined
解决方法

第一步:修正GetProfile函数的内部逻辑,正确返回接口数据

const GetProfile = async (username) => {
  const resp = await fetch(`${host}/api/v1/getprofile/${username}`);
  // 直接返回解析后的JSON数据,async函数会自动把它包装为Promise
  return resp.json();
};

第二步:使用异步方式调用函数获取结果,两种可选方案

方案1:用.then链式调用获取结果

GetProfile("username").then(profile => {
  // 此处即可拿到预期的接口返回数据,后续业务逻辑写在回调内
  console.log(profile);
}).catch(err => {
  // 捕获请求失败、JSON解析失败等异常
  console.error("获取用户信息失败:", err);
});

方案2:在其他async函数内用await调用

const handleGetProfile = async () => {
  try {
    const profile = await GetProfile("username");
    // 此处即可拿到预期的接口返回数据
    console.log(profile);
  } catch (err) {
    console.error("获取用户信息失败:", err);
  }
};

// 执行触发函数
handleGetProfile();

内容的提问来源于stack exchange,提问作者RoyalBosS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:39:02