【问题标题】:return is not working in async await function in react jsreturn 在反应 js 中的异步等待功能中不起作用
【发布时间】:2020-12-31 12:22:36
【问题描述】:

我想从另一个函数中获取结果,因为我使用了异步等待,函数但它没有返回数据,这里我已经上传了代码,任何人都可以检查我的代码并帮助解决这个问题,我已调用此函数 data_json = await this.get_json_data(url_string); 但我没有从中获得任何返回数据

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoaded: false
    };
  }

  async get_json_data(url_string) {
    await fetch("https://cors-anywhere.herokuapp.com/" + url_string)
      .then(res => res.text())
      .then(
        result => {
          let final_data = JSON.parse(result);
          return final_data;
        },
        error => {}
      );
  }

  async componentDidMount() {
    let data_json = "";
    let url_string = location.search.split("url=")[1];
    if (typeof url_string != "undefined" && url_string != undefined) {
      data_json = await this.get_json_data(url_string);
      //console.log("get result")
      //console.log(data_json)
    } else {
      data_json = require("./data.json");
    }
  }
}

【问题讨论】:

  • 你试过res.json()而不是res.text()吗?有了这个,你不应该需要JSON.parse(result)

标签: reactjs react-redux


【解决方案1】:

data_json 变量为空的原因可能是因为您没有从get_json_data 函数返回任何内容。在您的 await fetch 语句中添加一个返回。

// Add the return here:
return await fetch("https://cors-anywhere.herokuapp.com/" + url_string)
  .then(res => res.text())
  .then(
    result => {
      let final_data = JSON.parse(result);
      return final_data;
    },
    error => {}
  );

【讨论】:

    【解决方案2】:

    这是因为你在一个.then()方法回调中,return语句只对下一个.then()有效。为了说明这一点,我创建了一个fiddle

    如果你想让你的函数返回你获取的数据,你可以尝试实现相同的逻辑,但只使用asyncawait

    async get_json_data(url_string) {
        const res = await fetch("https://cors-anywhere.herokuapp.com/" + url_string)
        const final_data = await res.json()
        return final_data
    }
    

    或者,如果您想保留.then() 结构,您需要创建自己的Promise

    get_json_data(url_string) {
        return new Promise(resolve => {
          fetch("https://cors-anywhere.herokuapp.com/" + url_string)
          .then(res => res.text())
          .then(
            (result) => {
              let final_data = JSON.parse(result);
              resolve(final_data);
            },
            (error) => {
            }
          )
        })
    }
    

    【讨论】:

      【解决方案3】:

      要调用 asynchronous function 你可以这样做:

      (async () => {
        console.log(await get_json_data())
      })()
      

      【讨论】:

        猜你喜欢
        • 2020-06-30
        • 1970-01-01
        • 2019-05-18
        • 1970-01-01
        • 1970-01-01
        • 2021-08-23
        • 2017-02-06
        • 2019-05-04
        相关资源
        最近更新 更多