【问题标题】:How to call another method only after first method is completly done仅在第一个方法完全完成后如何调用另一个方法
【发布时间】:2020-01-11 13:12:27
【问题描述】:

我有一种情况,我需要在一个方法中使用数组,该方法之前在第一个方法中填充。

我需要在componentDidMount 上执行这两种方法,例如加载国家/地区,然后在下拉列表中加载当前国家/地区的城镇。是这样的。

假设我需要分别调用这两种方法:

async componentDidMount() {
      this.loadCountries();
      this.loadCities(this.state.currentCountry.id);
}

如何确定第一种方法已执行完毕,因为我需要在第二种方法中使用国家/地区数组 countries[],

现在我从服务器检索情况数据,但第二种方法不知道它,因为数据可能是异步检索的,仅此而已..

谢谢大家

干杯

【问题讨论】:

  • 在函数调用前使用await,即await this.loadCountires()
  • @CodeManiac 你能发布完整的例子吗:)
  • @CodeManiac 你能把它作为答案发布,这样我就可以接受了吗?

标签: javascript reactjs ecmascript-6 components


【解决方案1】:

只有在第一个函数完成后,您才能使用async/await 方法调用第二个函数。

这是你的 sn-p 。

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

【讨论】:

  • await this.countries = this.loadCountries(); 不起作用。
【解决方案2】:

如果你在第一种方法中返回的是全局 coutries[] 列表,那么第二种方法会知道

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 2014-03-21
    • 2021-12-24
    • 2021-02-19
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多