此简化代码:
qtmList = new QTMList();
qtmList.QTMMain = lstQTMmain;
qtmList.QTM = lstQTM;
qtmList.QTMStats = lstQTMStats;
无法解决。
如果将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)
,它将起作用。有什么想法吗?
答案 0 :(得分:2)
要返回的项目(this
)具有.then
方法,并且Promise解析器(resolve
)看到了这一点,认为您使用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)
})