【发布时间】:2020-10-08 23:46:21
【问题描述】:
我正在尝试从响应中的端点获取数据,但不知道如何等待被调用函数返回,然后将光标传递到下一行。
FetchData.js
// ...
componentDidMount () {
const url = 'http...';
const options = {
headers: {'Content-Type': 'application/json'},
method: 'GET'
}
const data = fetchDataFromUrl(url, options);
this.setState({ item: data },
() => this.updateItem())
}
console.log(this.state.item)
// ...
fetchData.js
export const fetchDataFromUrl = (url, options) => {
const repsonse = fetch(url, options)
.then(res => res.json())
.then(data => {
return data
})
}
这确实返回了data,但是在console.log() 中我得到了未定义,一段时间后(即在其他一些函数中)我能够看到data 的内容。如何等待fetchDataFromUrl 函数在状态更新之前获取数据。我用了
const data = async() => fetchDataFromUrl(url, options); 但没有帮助。
【问题讨论】:
-
Fetch is asynchronous.你试过等待
await fetch(...)吗? -
fetchDataFromUrl没有返回语句 -
我想我已经以更 Python 的方式做到了@Quentin
标签: javascript reactjs function async-await