这个简化的代码:
class A {
constructor() {
this.promise = new Promise(async resolve => {
this.resolve = resolve
})
}
then() {
this.promise.then(...arguments)
this.resolve(this)
}
}
const x = new A()
x.then(res => {
console.log(res)
})
无法解决。
如果将this.resolve(this)
更改为this.resolve('done')
,则可以使用。有什么想法?
返回的项目( this
(具有.then
方法,而Promise Resolver(resolve
(看到您认为您是用承诺称呼的,因此它试图解决该承诺也:
class A {
constructor() {
this.promise = new Promise(async resolve => {
this.resolve = resolve
await setTimeout(() => {
this.x = 1
}, 1000)
})
}
then() {
this.promise.then(...arguments)
this.fin()
console.log('then running');
}
fin() {
this.resolve(this)
}
}
const x = new A()
x.then(res => {
console.log(res)
})
一种可能的解决方案是使用 wraps this
的对象调用 resolve
,以使解析器函数看不到 .then
方法并尝试将其解开:
class A {
constructor() {
this.promise = new Promise(async resolve => {
this.resolve = resolve
await setTimeout(() => {
this.x = 1
}, 1000)
})
}
then() {
this.promise.then(...arguments)
return this.fin();
}
fin() {
this.resolve({ result: this })
}
}
const x = new A()
x.then(res => {
console.log(res.result)
})