Javascript 如何在承诺内抛出例外?
有一个处理扫描响应的函数:Javascript 如何在承诺内抛出例外?,javascript,typescript,promise,Javascript,Typescript,Promise,有一个处理扫描响应的函数: export const handleScanResponse = ( scanResponse: IScanResponse, visitors: IVisitor[] ): Promise<IVisitor | any> => { return new Promise((resolve, reject) => { if (!scanResponse || scanResponse.errorDesc !== "
export const handleScanResponse = (
scanResponse: IScanResponse,
visitors: IVisitor[]
): Promise<IVisitor | any> => {
return new Promise((resolve, reject) => {
if (!scanResponse || scanResponse.errorDesc !== "SUCCESS")
throw new Error("Scane response is empty!");
const found = visitors.find((p: IVisitor) => {
if (scanResponse && "qrcode" in scanResponse) {
return (
p.code && p.code.toLowerCase() === scanResponse.qrcode.toLowerCase()
);
} else {
return (
p.document_number &&
scanResponse.document_number &&
p.document_number.toLowerCase() ===
scanResponse.document_number.toLowerCase()
);
}
});
if (found) resolve(found);
reject(scanResponse);
}).catch((e) => console.log(e));
};
如何正确地做到这一点?为什么尽管有异常,我总是去
。然后((foundVisitor)=>这个.visitorWasFound(foundVisitor)
?当一个.catch
被添加到承诺链的末尾,并且有东西抛出时,整个承诺链将得到解决而不是拒绝。您的
.catch((e) => console.log(e));
正在将拒绝变成解决方案;handleScanResponse
返回的承诺永远不会拒绝
只在您能够合理处理错误的地方捕获错误。在这里,只需省去。catch
,它就可以按需要工作;这样,被拒绝的承诺就会渗透到调用方,而您的
).then(
(foundVisitor) => this.visitorWasFound(foundVisitor),
(scanResponse) => this.visitorNotFound(scanResponse)
);
我会处理好的
也就是说,这段代码中似乎没有任何异步现象。我建议完全删除承诺。那么,如果出现错误,什么时候使用catch?–您使用catch来捕获错误。但这不是您希望在方法中实现的。您希望抛出错误。您在希望处理错误的地方捕获错误。@AliceMessis Y只有当您能够合理地处理错误时,您才应该
.catch
。例如,如果您确实需要承诺,您可以使用.catch((scanResponse)=>this.visitorNotFound(scanResponse))
-在这里,您可以对错误采取有用的措施。相比之下,只记录错误的.catch
并不是真正有用的。@AliceMessis还检查了这一点:通常您需要.catch(
而不是。然后(onSuccess,onFail)
。在Promise构造函数中,您必须解析()
或拒绝()
。在.then()
和.catch()
回调中,必须返回
或抛出
。
).then(
(foundVisitor) => this.visitorWasFound(foundVisitor),
(scanResponse) => this.visitorNotFound(scanResponse)
);