Promise 不能解决这个问题

Promise does not resolve this

此简化代码:

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)
})

一个可能的解决方案是使用 包装 的对象调用 resolve 而不是 this,这样解析器函数就看不到.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)
})