[英]Unhandled promise rejection warning returning null
我似乎有一个无法处理的诺言拒绝,我找不到...
我已经使用--trace-warnings
运行nodejs,并且在脚本顶部有以下代码:
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
console.log(p)
console.log(reason)
});
当诺言被拒绝时,我看到:
Unhandled Rejection at: Promise { <rejected> null } reason: null
Promise { <rejected> null }
null
我检查了一些异步函数和诺言,它们都有.catch()
的...这里到底发生了什么? 我如何找出拒绝的来源?
一些代码。 我的课堂上有以下异步函数:
async loop() {
console.log("starting loop")
if ( this.state != this.STOPPED ) {
switch (this.case) {
case this.POLLING:
console.log("Start polling")
await Promise.all(this.symbols.map(symbol => {
return this.fetch(symbol)
})).then(() => {
...
}).catch(error => {
...
})
for (let symbol of this.symbols) {
await this.process(symbol).then(() => {
...
}).catch(error => {
...
})
} //for
for (let openPosition of this.openPositions) {
this.log.push(openPosition.toLogString())
}
console.log("end polling")
break
} //state selection case
console.log(this.log.formatTimestamp(Date.now()))
this.log.dump()
this.log.clear()
console.log("done dumping")
setTimeout(this.loop.bind(this), 0)
}
}
奇怪的是输出,该输出重复:
starting loop
Start polling
end polling
done dumping
Unhandled Rejection at: Promise { <rejected> null } reason: null
Promise { <rejected> null }
null
该警告基本上显示在setTimeout()
调用上。 不知道为什么这是一个问题。 另外值得注意的是,我似乎得到不同数量的promise拒绝,这取决于this.OpenPositions
数组中有多少个元素。 对于n> 1,我得到n-1个错误,其中n是元素数。
我不知道这是问题所在,但似乎是几种可能性之一。
async
函数返回一个Promise,这意味着您的loop()
函数返回一个Promise。 如果此函数中有一个错误(不是其他promise的一部分),那么这些错误将变成未处理的拒绝。 考虑:
let obj = { count: 0, async loop() { this.count++ console.log("running: ", this.count) if (this.count == 2) throw ("whoops") if (this.count < 2) { setTimeout(this.loop.bind(this), 0) } } } obj.loop()
即使函数中没有promise, throw()
也会导致未处理的promise拒绝。 (我认为该代码段会吞下它们,但您可以在控制台中看到它)
要捕获这些,您需要catch
loop()
本身。 在超时中调用它的方式可能不太方便,但是您可以执行以下操作:
let obj = { count: 0, async loop() { this.count++ console.log("running: ", this.count) if (this.count == 2) throw ("whoops") if (this.count < 2) { if (this.count < 2) { setTimeout(() => this.loop() .catch(err => console.log("caught error: ", err)), 0) } } return this.count } } obj.loop().catch(err => console.log("caught error outside: ", err))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.