2017-10-25 24 views
1

です:約束チェーン、「これは」私は、次のコード(簡体字)を持っている私のプロバイダで、未定義

initiateAPI(): Promise<any> { 
     return this.method1() 
     .then(this.method1) 
     .then(this.method2) 
     .catch(console.log); 
    } 

両方法1法2次のように方法は、約束を返す:

method1() : Promise<any> { 
    console.log("this in method 1",this); 
    return new Promise((resolve, reject) => { 
     this.anotherProvider.getData().then((data) => { 
     if(!data) { 
      reject("Data not found"); 
     } 
     resolve(data); 
     }); 
    }); 
    } 

method2() : Promise<any> { 
    console.log("this in method 2",this); 
    return new Promise((resolve, reject) => { 
     this.thirdProvider.getData().then((data) => { 
     if(!data) { 
      reject("Data not found"); 
     } 
     resolve(data); 
     }); 
    }); 
    } 

第1の方法(方法1)が正しく実行され、第2の方法(方法2)が呼び出され、 予想通り。問題は、2番目の方法でthisが未定義であることです。

次のように私はまた、チェーンに約束を試してみました:

initiateAPI(): Promise<any> { 
     return this.method1() 
     .then(() => this.method1) 
     .then(() => this.method2) 
     .catch(console.log); 
    } 

しかし、問題は同じまま。

thisはその価値をどのように保つことができますか?

答えて

1

メソッドは旧式のfunction関数として実装されているため、矢印関数としてではなく、thisはメソッドの呼び出し方法によって決まります。関数リファレンスをthenコールバックとして指定すると、thisundefined(またはグローバルオブジェクトがスローキーモード)になります。

あなたがそれを望むようthisを維持するには、少なくとも2つの方法があります。

initiateAPI(): Promise<any> { 
    return this.method1() 
     .then(_ => this.method1()) 
     .then(_ => this.method2()) 
     .catch(console.log); 
} 

か:

initiateAPI(): Promise<any> { 
    return this.method1() 
     .then(this.method1.bind(this)) 
     .then(this.method2.bind(this)) 
     .catch(console.log); 
} 
は、
関連する問題