I have a situation where I need to use array in a method, which is previously populated in first method.
I need both methods to execute on componentDidMount
, for example load countries, after that load towns for current country in droopdown. It goes something like that.
Lets say I need to call this 2 methods separately:
async componentDidMount() {
this.loadCountries();
this.loadCities(this.state.currentCountry.id);
}
How can I be sure first method is done with executing because I need to use countries array countries[],
in my second method.
Right now I have situation data is retrieved from a server but second method is not aware of it becasue data are retrieved asynhronous probably, and that's it..
Thanks guys
Cheers
You can use the async/await
method to call second function only after first function get complete .
here is your snippet .
var countries = [];
async componentDidMount() {
await this.countries = this.loadCountries(); // you will have countries values in 'this.countries'. Which you can access it further .
await this.loadCities(this.state.currentCountry.id);
}
如果您在第一种方法中返回的是coutries []的全局列表,则第二种方法将知道
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.