Javascript Class 内的承诺
Javascript Promise within Class
Fun with promises today ...我想弄清楚为什么我不能参考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();
Fun with promises today ...我想弄清楚为什么我不能参考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();