【问题标题】:Issue with Sequential function calls using async await使用异步等待的顺序函数调用问题
【发布时间】:2019-07-11 02:42:03
【问题描述】:

我发现当我尝试调用函数时,需要先调用 initializeItems()。但是 checkList() 在 initializeItems() 之前被调用

  initializeItems() {

    this.dataService.readLocalData().subscribe( data => {
      console.log('Local Data');
      this.items = data;
      // console.log(this.items);
      this.tempItems = [];
      for (const i of this.items.material ){
        console.log(i['material-name']);
        this.tempItems.push( i['material-name'] );
      }
      console.log('***********************************************');
      console.log(this.tempItems);
    });
  }

  checkList(ev: any){
    // set val to the value of the searchbar
    const val = ev.target.value;
    console.log(val);
    console.log(this.tempItems);
    // if the value is an empty string don't filter the items
    if (val && val.trim() !== '') {
      this.tempItems = this.tempItems.filter((item) => {
        return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      });
    }
  }

  async getItems(ev: any) {
    // Reset items back to all of the items
    await this.initializeItems(); //This need to execute first
    await this.checkList(ev); //But this getting executed
  }

如果函数按顺序调用。我的结果是

initializeItems()

变量 tempItems 将是//完整列表

然后

检查清单()

变量 tempItems 将是//从可搜索下拉列表中过滤的列表

【问题讨论】:

  • InitializeItems 不返回承诺,因此await this.initializeItems() 中的await 并没有真正做任何事情。你想成为 initializeItems “完成”的指标是什么?订阅回调何时运行完成?
  • 可能知道如何重写我的代码。我已经被困在这里 4 个小时了。

标签: typescript ionic4


【解决方案1】:

await 用于与承诺一起使用。由于 initializeItems 不返回承诺,因此 await 实际上并没有等待任何东西。您需要修改 initializeItems 以返回承诺。我的猜测是,您希望订阅回调只被调用一次,并且此时承诺应该解决,所以您想要这样做:

initializeItems() {
  return new Promise((resolve) => { // <---- creating a promise
    this.dataService.readLocalData().subscribe( data => {
      console.log('Local Data');
      this.items = data;
      // console.log(this.items);
      this.tempItems = [];
      for (const i of this.items.material ){
        console.log(i['material-name']);
        this.tempItems.push( i['material-name'] );
      }
      console.log('***********************************************');
      console.log(this.tempItems);
      resolve(); // <-- resolving the promise
    });
  }
}

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多