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
はその価値をどのように保つことができますか?