私は2番目の約束でクラスプロパティを参照したいと思います。しかし、クラス関数pTwoでは、 'this'は未定義です。私は約束の範囲にいることを理解しています。私はどのようにPromiseChainインスタンスのスコープにアクセスできますか?ES6クラスPromiseチェーン - アクセス 'this'
ES6と本来の約束を使用しています。
class PromiseChain {
constructor(){
this.food = 'Pasta';
this.type = 'Italian';
}
pOne() {
console.log('pOne');
return Promise.resolve();
}
pTwo() {
console.log('pTwo');
try {
console.log(this.food);
} catch (e) {
// can't read 'food' of undefined!
console.log(e);
}
return Promise.reject()
}
work() {
console.log('Get to work!');
this.pOne().then(this.pTwo).catch((error) => {
console.log(error);
})
}
}
new PromiseChain().work();
ちょっと@Alex、まさに精神的なブーストのおかげで!あなたが10の約束を結んでいるシナリオでは、それぞれを少し冗長に見える.bind(this)を追加すると、そうするクリーナーの方法がありますか? – ebbflowgo
もっとクリーンな方法を見つけたら、私は最も興味をそそられるだろう!残念なことに私のコードは '.bind'に苦しんでいます。 :) – Alex
できます:)もう一度ありがとう! – ebbflowgo