Reputation: 33
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));
}
Upvotes: 0
Views: 55
Reputation: 5953
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));
}
Upvotes: 2