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

async await与promise链未等待请求决议就返回undefined如何解决?

问题核心

你的代码中__sendRequest方法没有将内部axios请求的Promise实例返回,也没有等待该请求执行完成,导致外层的await只会等待Auth.currentSession()执行结束,不会等待接口返回,最终拿到的结果就是undefined。

修复方案

推荐统一使用async/await语法,避免混用await和.then回调导致逻辑不清晰,修改后的__sendRequest代码如下:

async __sendRequest(url, method) {
  try {
    // 等待鉴权信息获取完成
    const sess = await Auth.currentSession();
    console.log(sess.getIdToken().getJwtToken());
    // 等待接口请求完成
    const response = await axios({
      method: method,
      url: process.env.REACT_APP_USER_URL + url,
      headers: {
        "X-TOKEN-ID": sess.getIdToken().getJwtToken(),
        "addresseeType": "P",
        "content-type": "application/json"
      }
    });
    console.log(response);
    // 正常返回接口结果
    return response;
  } catch (err) {
    console.error(err);
    // 可以选择抛出错误,让上层调用处可以捕获异常做自定义处理
    throw err;
  }
}

如果你希望保留.then的写法,需要把两层Promise都正确返回,修改如下:

async __sendRequest(url, method) {
  // 第一层:返回Auth.currentSession的执行结果
  return await Auth.currentSession().then(sess => {
    console.log(sess.getIdToken().getJwtToken())
    // 第二层:返回axios请求的Promise实例
    return axios({
      method: method,
      url: process.env.REACT_APP_USER_URL + url,
      headers: {
        "X-TOKEN-ID": sess.getIdToken().getJwtToken(),
        "addresseeType": "P",
        "content-type": "application/json"
      }
    }).then(function (response) {
      console.log(response)
      return response
    }).catch(err => {
      console.error(err);
    })
  })
}

额外优化建议

你当前useEffect中的变量名和函数名重名了,容易引发逻辑混淆,建议修改:

useEffect(() => {
    async function fetchMessages() {
        const messages = await ApiService.getMessages();
        console.log(messages)
    }
    fetchMessages();
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:06:00