【发布时间】:2019-12-15 05:55:33
【问题描述】:
这不是任何概念问题。只是想纠正我的逻辑方面。
案例一:
try {
var to = await new IamErrorAlways()
if (to && to instanceof Error) return to // is this correct way to handle.
} catch (error) {
// report failure.
return error
}
案例 2:
try {
var to = await new IamErrorAlways()
if (!to) throw new error('Expected to to return error') // or is this correct way to handle.
} catch (error) {
// report failure.
return error // <---- catch will return awaited error
}
哪一个好。
【问题讨论】:
-
很可能没有一个是正确的。
await new …永远不会有意义,除非构造函数产生一个 thenable,同样!to永远不会为真,除非new IamErrorAlways()是一个 thenable。 -
:p 当你的构造函数被等待并且 !to 可能是 this 本身时它是有意义的......作为回报,它不应该是空的
-
“当你的构造函数被等待时”是什么意思?
-
构造函数总是立即返回,然后最终得到解决。我同意...但是对于您希望在函数体内调用 await 方法而不是必须用 async 将其包装起来的情况...如果您这样做,那么使用 await new functionName() 就变得很明显了,否则您必须解决它。
-
不清楚你的意思,但这听起来不是使用
await new的唯一原因,这是我提到的thenable 东西。如果!('then' in new IamErrorAlways()),var to = await new IamErrorAlways();完全等同于await; var to = new IamErrorAlways();,并且可能等同于var to = new IamErrorAlways();。
标签: javascript node.js error-handling es6-promise