javascript - 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)
})
一种可能的解决方案是使用包装的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)
})
推荐阅读
- java - 命令消息 - 分类设计问题
- php - Xdebug 连接不适用于 PhpStorm 和 Docker
- xslt - 如何根据其他节点的属性值删除 XML 节点
- postgresql - 将 jira 用户转移到在 docker 中运行的 jira-crowd-postgresql 容器中的人群
- apache-kafka - 如何使用 CLI/命令行中的用户名和密码保护 kafka 主题?
- java - 按条目的递减顺序生成列表的笛卡尔积(条目为正数,列表已排序)
- html - Safari 忽略 flex 容器中子元素的绝对高度
- vb.net - VB.net web api如何获取json变量作为参数?
- wpf - 使用 DataTrigger 显示控件的 WPF 在 TabOrder 中跳过它
- python - 正确使用python中的可见性属性,例如对象变量和方法