Promise 链接,"this" 未定义
Promise chaining, "this" is undefined
在我的提供商中,我有以下代码(简化):
initiateAPI(): Promise<any> {
return this.method1()
.then(this.method1)
.then(this.method2)
.catch(console.log);
}
method1和method2两个方法return一个Promise,如下:
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);
});
});
}
第一个方法 (method1) 正确执行,第二个方法 (method2) 被调用,正如预期的那样。问题是 this
在第二种方法中未定义。
我也试过如下链接承诺:
initiateAPI(): Promise<any> {
return this.method1()
.then(() => this.method1)
.then(() => this.method2)
.catch(console.log);
}
但问题依旧。
如何让 this
保持其价值?
方法实现为老式的 function
函数,而不是箭头函数,这意味着 this
由调用方法的方式决定。当您提供函数引用作为 then
回调时,this
将是 undefined
(或草率模式下的全局对象)。
至少有两种方法可以让 this
随心所欲:
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);
}
在我的提供商中,我有以下代码(简化):
initiateAPI(): Promise<any> {
return this.method1()
.then(this.method1)
.then(this.method2)
.catch(console.log);
}
method1和method2两个方法return一个Promise,如下:
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);
});
});
}
第一个方法 (method1) 正确执行,第二个方法 (method2) 被调用,正如预期的那样。问题是 this
在第二种方法中未定义。
我也试过如下链接承诺:
initiateAPI(): Promise<any> {
return this.method1()
.then(() => this.method1)
.then(() => this.method2)
.catch(console.log);
}
但问题依旧。
如何让 this
保持其价值?
方法实现为老式的 function
函数,而不是箭头函数,这意味着 this
由调用方法的方式决定。当您提供函数引用作为 then
回调时,this
将是 undefined
(或草率模式下的全局对象)。
至少有两种方法可以让 this
随心所欲:
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);
}