首页 > 解决方案 > Promise 不能解决这个问题

问题描述

这个简化的代码:

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')工作原理。任何想法为什么?

标签: javascriptes6-promise

解决方案


返回的项目 ( 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)
})


推荐阅读