Javascript 承诺仍然挂起,即使使用.then()
我正在使用axios从后端检索数据,但承诺仍在等待中 我使用了.then()甚至异步和等待。我使用的是.then(res=>res.data),因为我知道每个承诺都有保存检索到的数据的“data”键,之后它将以这种方式返回。我还绑定了构造函数中的函数Javascript 承诺仍然挂起,即使使用.then(),javascript,reactjs,asynchronous,promise,Javascript,Reactjs,Asynchronous,Promise,我正在使用axios从后端检索数据,但承诺仍在等待中 我使用了.then()甚至异步和等待。我使用的是.then(res=>res.data),因为我知道每个承诺都有保存检索到的数据的“data”键,之后它将以这种方式返回。我还绑定了构造函数中的函数 async getTrackInfo() { return await axios.get('http://localhost:60231/api/values') .then(res => res.data); }; com
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
});
}
但不幸的是,它返回的是未定义的。以下代码可以工作:-
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
});
}
您需要
const data=wait this.getTrackInfo()代码>async
函数始终返回承诺。承诺是管理异步操作的标准方式async
/await
提供了用于管理它们的过程式语法。它们不会阻止异步操作的执行asynchronous@ChrisG-那会出错的componentDidMount
不是async
@Quentin非常确定将componentDidMount()
更改为async
的指令隐含在Chris的评论中……要使用Wait
,您必须使函数(在这种情况下,componentDidMount
)是异步的。一个小挑剔,返回等待
中的等待
是多余的。还可以从getTrackInfo()
中删除async
,并返回axios…
。它也会做同样的事情。