【发布时间】: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