【问题标题】:How to wait for JavaScript function to complete in react? [duplicate]如何等待 JavaScript 函数在反应中完成? [复制]
【发布时间】: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


【解决方案1】:

您可以简单地使用、异步和等待您的要求

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多