2016-04-16 10 views
0

私はかなり単純な例であると思われることをしようとしています。これは、I型2にtypescriptで書かれています。ループが完了した後のIonic2/TypeScriptのクリア変数

2つのhello配列をループしたいと思います。ループが終了したら、私はこのメッセージをクリアしたい。私はrunHello()関数を持っています。私はforループが最初に実行され、次にthis.message = ""を実行すると考えましたが、代わりにループが完了する前に実行されます。

私はこれについて多くのことを尋ね、約束以外の多くの助けを見つけることができませんでした。私はこれが少し複雑になると思っていて、約束事はイオニックか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 =""; 
    // } 

    } 

答えて

0

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 = ""; 
      } 
     } 

    } 
関連する問題