Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何等待JavaScript函数在react中完成?_Javascript_Reactjs_Function_Async Await - Fatal编程技术网

如何等待JavaScript函数在react中完成?

如何等待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' }

我试图从react中的端点获取数据,但不知道如何确切地等待被调用函数返回,然后将光标传递到下一行

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 
    })
}
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
}

你试过Wait
Wait fetch(…)
fetchDataFromUrl
没有返回语句我想我用了一种更像python的方式@Quentin