【发布时间】:2019-06-05 05:58:12
【问题描述】:
试图将我的回复转换为 json。我不太确定我收到TypeError: response.json is not a function 错误。有人可以指出我正确的方向。提前致谢。
componentDidMount(){
this.timingFunction = setInterval(() => this.getAllStations(), 1000);
}
async getAllStations(){
try{
const response = await(`http:api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
const data = await response.json();
console.log(`Here: ${data}`)
}catch(e){
console.log(`Error: ${e}`)
}
}
我希望看到 json 响应,但收到了错误消息。 编辑:在 response.json() 前面添加等待;却无处可去。
【问题讨论】:
-
为什么使用 async.. 可以使用 promises 来完成..
-
@user7417866 确实如此。但是,这也应该适用于异步。
-
async 和 await 用于承诺不用于从服务器 / url 获取数据,最好的使用方法是 ajax 用于服务器获取代码。
-
更具体地说,await 会导致异步函数暂停,直到 Promise 完成,但在您的情况下,它从 URL 获取响应而不是 Promise
标签: javascript reactjs