循环完成后,Ionic2/TypeScript清除变量

Ionic2/TypeScript clear variable after loop is complete

本文关键字:TypeScript 清除 变量 Ionic2 循环      更新时间:2023-09-26

我正在尝试做我认为应该是一个非常简单的例子。这是用Ionic 2用打字本写的。

我想循环遍历2个hello数组。循环完成后,我想清除这个.message。我有一个runHello()函数。我原以为for循环会先运行,然后运行this.message=",但它在循环完成之前运行。

我在谷歌上搜索了很多关于这件事的信息,除了Promises之外,找不到其他任何帮助。我认为这会有点复杂,而且承诺似乎不适用于Ionic或Typescript。

我有一个resetHello()函数,如果我不能让它工作,我会把它绑定到一个按钮上。

学习编程还是个新手。任何帮助都将不胜感激!

export class Page1 {
  message: string = "";
  helloArr: Array<any>;
  constructor() {}
  sayHello(){
   setTimeout( ()=>{
      this.message ="Hello";
        }, 2000);
    };
  sayHello2(){
   setTimeout( ()=>{
      this.message ="Hello2";
    }, 3000);
  };
  runHello(){
    this.helloArr = [this.sayHello(), this.sayHello2()];
      for(let func of this.helloArr){
        func;
      };
      this.message = "this runs before for loop is done";
  }
  // resetHello(){
    //   this.message ="";
   // }
  }

setTimeout调用是异步的,因此在检查是否应重置this.message之前,必须等待它们的回调运行。

    export class Page1 {
        message: string = "";
        helloArr: Array < any > ;
        count = 0;
        constructor() {}
        sayHello() {
            setTimeout(() => {
                this.message = "Hello";
                decrement()
            }, 2000);
        };
        sayHello2() {
            setTimeout(() => {
                this.message = "Hello2";
                decrement();
            }, 3000);
        };
        runHello() {
            this.helloArr = [this.sayHello(), this.sayHello2()];
            this.count = this.helloArr.length;
            for (let func of this.helloArr) {
                func;
            };
            // this.message = "this runs before for loop is done";
        }
        decrement() {
            this.count = --this.count;
            if (this.count == 0) {
                this.message = "";
            }
        }
    }