0

I used the componentDidMount method as async and made some operations, but the system returned to me the state of the first entry instead of working async.

  async componentDidMount() {
    await this.getCityList();
    console.log(this.state.cities)
    await this.currentLocation();
  }

At this point the console log turns empty. however, when I normally check, data input is observed, but comes after a while. The same applies to the currentloc method. These methods draw some data from the database.

and city function:

  getCityList() {
    let link = "http://..../Cities";
    fetch(link)
      .then(response => response.json())
      .then(res => {
        this.setState({
          cities: res,
        })
      })
      .catch(error => console.warn(":::::::::", error));
  }
VillageTech
  • 1,968
  • 8
  • 18

1 Answers1

2

You need to return the Promise inside getCityList method.

Without return:

async function foo() {
  const result = await baz();
  console.log('Result', result);

  console.log('Should be called after baz!');
}

function baz() {
  new Promise((resolve) => {
    setTimeout(() => resolve('Hello from baz!'), 3000);
  });
}

foo();

With return:

async function foo() {
  const result = await baz();
  console.log('Result', result);

  console.log('Should be called after baz!');
}

function baz() {
  return new Promise((resolve) => {
    setTimeout(() => resolve('Hello from baz!'), 3000);
  });
}

foo();

Following is the correct way to do it for await to work (with your example snippet):

 getCityList() {
    let link = "http://..../Cities";
    return fetch(link) // Added a return here
      .then(response => response.json())
      .then(res => {
        this.setState({
          cities: res,
        })
      })
      .catch(error => console.warn(":::::::::", error));
  }
Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38
  • it's solved half of my problem but I couldn't solve other part. My 2. function is using google API and nested functions how can I use there? [link](https://stackoverflow.com/questions/59413822/react-native-using-nested-async-not-working-properly) – Artun Burak Mecik Dec 19 '19 at 16:46
  • @ArtunBurakMecik I would suggest creating a separate question for that. You can link me to the question here. – Umair Sarfraz Dec 19 '19 at 16:48