简体   繁体   English

只有在第一个方法完成后才能调用另一个方法

[英]How to call another method only after first method is completly done

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. 我需要两种方法都可以在componentDidMount上执行,例如加载国家/地区,然后在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. 我如何确定第一种方法是执行完毕,因为在第二种方法中我需要使用countries array countries[],

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 . 只有在第一个函数完成后,才能使用async/await方法调用第二个函数。

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 []的全局列表,则第二种方法将知道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM