今天的承诺很有趣。。。我试图弄清楚为什么我不能引用this.promise来用另一个方法解决它,它总是空的。
任何启示都值得赞赏:(
export default class Example {
constructor() {
this.promise = null
}
test() {
this.promise = new Promise((resolve, reject) => {
this.something()
}).then(resolve => {
// resolved, do something else
}).catch(reject => {
console.log('reject', reject)
})
}
something() {
this.promise.resolve()
}
}
您正试图在something
中使用this.promise
,然后它的值才会从null
更改。另一种方法是传递resolve
作为参数:
class Example {
constructor() {
this.promise = null;
}
test() {
this.promise = new Promise((resolve, reject) => {
this.something(resolve);
}).then(result => {
console.log('resolve', result);
}).catch(error => {
console.log('reject', error);
});
}
something(resolve) {
resolve(1);
}
}
const example = new Example();
example.test();