【问题标题】:Promise still pending even though using .then() [duplicate]即使使用 .then(),承诺仍然悬而未决 [重复]
【发布时间】:2019-04-24 00:09:08
【问题描述】:

我正在使用 axios 从我的后端检索数据,但承诺仍在等待中。

我使用过 .then() 甚至 async 和 await。我正在使用 .then(res => res.data) 因为我知道每个承诺都有“数据”键来保存检索到的数据,之后它将以这种方式返回。我还在构造函数中绑定了函数!

async getTrackInfo() {
  return await axios.get('http://localhost:60231/api/values')
    .then(res => res.data);
};


componentDidMount() {
  const data = this.getTrackInfo();
  console.log(data);

  this.setState({
    tracks: data
  });
}

但不幸的是,它返回 undefined。

【问题讨论】:

  • 你需要const data = await this.getTrackInfo();
  • async 函数总是返回一个承诺。 Promise 是管理异步操作的标准方法。 async/await 为您提供程序样式语法来管理它们。它们不会阻止异步操作异步
  • @ChrisG - 这会出错。 componentDidMount 不是 async
  • @Quentin 很确定将 componentDidMount() 更改为 async 的指令隐含在 Chris 的评论中......

标签: javascript reactjs asynchronous promise


【解决方案1】:

以下代码可以工作:-

async getTrackInfo() {
  return await axios.get('http://localhost:60231/api/values')
    .then(res => res.data);
};


async componentDidMount() { // Make this function async
  const data = await this.getTrackInfo(); // add await here
  console.log(data);

  this.setState({
    tracks: data
  });
}

【讨论】:

  • 要使用await,您必须创建函数(在本例中为componentDidMountasync
  • 一个小问题,return await 中的await 是多余的。不妨从getTrackInfo()return axios... 中删除async。它会做同样的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 2017-07-15
  • 2016-01-21
  • 2018-05-25
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多