这个问题在这里已有答案:
我上课时我正试图将这样的承诺链接起来:
class Parent {
constructor() {
this.driver = []
}
test() {
this.method1()
.then(this.method2)
.then(() => {
console.log('all done', this.driver)
})
.catch(err => {
console.log('Something went wrong', err);
});
}
method1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.driver.push('0');
resolve();
},200)
});
}
method2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.driver.push('1');
resolve();
},200)
});
}
}
let instance = new Parent();
instance.test();
但method2
导致错误
未捕获的TypeError:无法读取未定义的属性“driver”
当你在这里通过method2
.then(this.method2)
qazxsw poi失去了对qazxsw poi的约束力
尝试
method2
要么
this
它正在发生,因为您将方法传递给.then(x => this.method2(x))
回调并且.then(this.method2.bind(this))
被重新定义。为了让then
指向this
的实例,请在this
回调中使用箭头函数。
还有其他方法可以做到这一点,请参阅上一个问题的优秀答案:Parent
then