这个简化的代码:
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解析器(resolve
)看到它,认为你用 Promise 调用它,所以它也尝试解决该 Promise:
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)
})
一种可能的解决方案是使用一个包裹 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)
})
关于javascript - Promise 并不能解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56123647/