javascript - Promise 并不能解决这个问题

标签 javascript es6-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') ,它就会起作用。有什么想法吗?

最佳答案

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

相关文章:

javascript - jQuery - 模仿点击

php - 从 PHP 访问 JavaScript 变量

javascript - InfluxDB 写入事件监听器/触发器

javascript - Requirejs 在 define() 中加载不同的 js 文件

javascript - Reactjs 在特定时间后连续发送 Promise

javascript - soundcloud 嵌入中的时间和事件

javascript - 迭代数据并作为响应发送

javascript - Promise 从 `catch` 中调用 `then`

javascript - 在迭代到循环的下一次迭代之前完成 FOR 循环内的所有函数

node.js - 避免嵌套 promise