如何等待JavaScript函数在react中完成?
我试图从react中的端点获取数据,但不知道如何确切地等待被调用函数返回,然后将光标传递到下一行 FetchData.js如何等待JavaScript函数在react中完成?,javascript,reactjs,function,async-await,Javascript,Reactjs,Function,Async Await,我试图从react中的端点获取数据,但不知道如何确切地等待被调用函数返回,然后将光标传递到下一行 FetchData.js // ... componentDidMount () { const url = 'http...'; const options = { headers: {'Content-Type': 'application/json'}, method: 'GET' }
// ...
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)
// ...
export const fetchDataFromUrl = (url, options) => {
const repsonse = fetch(url, options)
.then(res => res.json())
.then(data => {
return data
})
}
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)
// ...
export const fetchDataFromUrl = (url, options) => {
const repsonse = fetch(url, options)
.then(res => res.json())
.then(data => {
return data
})
}
这确实会返回
数据
,但在console.log()中我没有定义,过了一段时间(即在其他函数中),我可以看到数据
内容。在状态更新之前,如何等待fetchDataFromUrl
函数获取数据。我曾经
const data=async()=>fetchDataFromUrl(url,选项)代码>但它没有帮助。您可以简单地使用、异步并等待您的需求
componentDidMount () {
this.getData()
}
getData= async()=>{
const url = 'http...';
const options = {
headers: {'Content-Type': 'application/json'},
method: 'GET'
}
const data = await fetchDataFromUrl(url, options);
this.setState({ item: data },
() => this.updateItem())
}
用户获取函数也应该是异步函数
export const fetchDataFromUrl = async(url, options) => {
const repsonse = await fetch(url, options);
return repsonse; //Modify you response
}
你试过WaitWait fetch(…)
?fetchDataFromUrl
没有返回语句我想我用了一种更像python的方式@Quentin