如何在异步函数调用中添加错误处理?
当前的打字稿代码有以下操作:
React.useEffect(() => {
if (prepAttrsRef.current) {
prepAttrsRef.current.addEventListener('documentstatechanged',
async (evt: CustomEvent<FlowDocumentState>) => {
if (evt.detail.draftState === 'all-changes-published') {
dispatch(updateIsFlowpublished(true));
let cleanSteps: readonly CleanStep[] = [];
if (prepAttrsRef.current) {
cleanSteps = await prepAttrsRef.current.getAllStepsOfTypeAsync('clean');
if (cleanSteps && cleanSteps.length > 0 && cleanSteps[0] !== undefined) {
await cleanSteps[0].selectAsync();
}
}
}
});
}
return () => {
//TBC: cleanup
};
}, []);
现在我们知道selectasync()
方法返回承诺:
selectAsync(): Promise<SelectResponse>
selectresponse
可以包含错误消息:
SelectResponse: { success: true } | { errorMessage: string; errorType: SelectError; success: false }
因此,在这种情况下,如何添加错误将代码处理到等待CleanSteps [0] .Selectasync();
? 是否应该在此处删除
关键字?
Currently the typescript code has this:
React.useEffect(() => {
if (prepAttrsRef.current) {
prepAttrsRef.current.addEventListener('documentstatechanged',
async (evt: CustomEvent<FlowDocumentState>) => {
if (evt.detail.draftState === 'all-changes-published') {
dispatch(updateIsFlowpublished(true));
let cleanSteps: readonly CleanStep[] = [];
if (prepAttrsRef.current) {
cleanSteps = await prepAttrsRef.current.getAllStepsOfTypeAsync('clean');
if (cleanSteps && cleanSteps.length > 0 && cleanSteps[0] !== undefined) {
await cleanSteps[0].selectAsync();
}
}
}
});
}
return () => {
//TBC: cleanup
};
}, []);
Now we know that selectAsync()
method returns a promise:
selectAsync(): Promise<SelectResponse>
And the SelectResponse
could contain error message:
SelectResponse: { success: true } | { errorMessage: string; errorType: SelectError; success: false }
So in this case, how to add error handling code to await cleanSteps[0].selectAsync();
? Should the await
keyword to be removed here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,基本上SelectAsync方法处理错误(抛出和错误的错误),并根据成功或故障返回响应对象。
您可以通过这种响应
并检查
它实际上取决于您在每种情况下要做什么。
如果您想知道如何处理async函数错误,那么您需要包装可能会引发错误的内容,然后尝试使用catch block
async/等待
So basically selectAsync method handles errors (those that are throw as and Error) and returns response object depending on success or failure.
You can get that response by
And check
It really depends on what you want to do in each scenario.
If you want to know how to handle async function errors in general then you need to wrap content that might throw an error with try catch block
Promise chain in async/await