我上了一堂课,试图像这样链接诺言:
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'
答案 0 :(得分:0)
当您在此处通过method2
.then(this.method2)
method2
失去了对this
的约束力
尝试
.then(x => this.method2(x))
或
.then(this.method2.bind(this))
答案 1 :(得分:0)
之所以发生,是因为您正在向then
回调传递方法,并且this
被重新定义。要使this
指向Parent
的实例,请在then
回调中使用箭头功能。
还有其他方法可以执行此操作,请参见上一个问题的出色答案:How to access the correct `this` inside a callback?
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();