这是一个更大问题的一部分,但是当类需要
promise
解析以获取数据。
以下操作将不起作用
this.promise
每次分配时,函数都已返回
this
class Test {
constructor(promise) {
this.promise = promise;
}
add(x) {
this.promise.then(y => {
this.promise = new Promise(resolve => {
resolve(x + y);
});
});
return this;
}
multiply(x) {
this.promise.then(y => {
this.promise = new Promise(resolve => {
resolve(x * y);
});
});
return this;
}
answer() {
this.promise.then(x => {
console.log(x);
});
}
}
function getNumber(num) {
const promise = new Promise(resolve => {
resolve(num);
});
return new Test(promise);
}
const num = getNumber(30);
num.add(20).multiply(2).answer();