Nikul Panchal
Nikul Panchal

Reputation: 1673

return is not working in async await function in react js

I want to get result from another function, for that i have used async await, function but it didn't return the data, here i have uploaded code, can anyone please check my code and help to resolve this issue,i have called this function data_json = await this.get_json_data(url_string); but i am not getting any return data from it

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

Upvotes: 0

Views: 12051

Answers (3)

Blessing
Blessing

Reputation: 2720

To call that asynchronous function you can do:

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

Upvotes: 2

Jap Mul
Jap Mul

Reputation: 18739

The reason your data_json variable is empty is probably because you aren't returning anything from your get_json_data function. Add a return to your await fetch statement.

// 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 => {}
  );

Upvotes: 4

Hurobaki
Hurobaki

Reputation: 4068

It's because you're in a .then() method callback, return statement will only work for the next .then(). To illustrate this I've create a fiddle

If you want to make your function return your fetched data you could try to implement same logic but using only async await.

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
}

Or if you want to keep .then() structure you need to create your own 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) => {
        }
      )
    })
}

Upvotes: 4

Related Questions