javascript - Variable is used before being assigned with fetch
问题描述
Typescript throws the following error on the second last line of my function:
Variable 'organizationInfoResponse' is used before being assigned.
I am not too sure how to omit that problem since I am assigning the organizationInfoResponse
inside a try catch block in a fetch. Can you point me in the right direction here please?
interface OrganizationInfoResponse {
organization_name: string;
organization_id: string;
errorCode?: string;
}
export const handleGetOrganization = async (
organizationName: string,
): Promise<OrganizationInfoResponse> => {
let organizationInfoResponse: OrganizationInfoResponse;
try {
const rawRes = await fetch(
`/sometestendpoint/${organizationName}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
organizationInfoResponse = await rawRes.json();
if (rawRes.status >= 400) {
if (organizationInfoResponse.errorCode === ErrorCodes.INVALID_ORG_NAME) {
throw new Error('Given Organization Name is invalid');
}
}
} catch (error) {
// Do something
}
return organizationInfoResponse;
};
解决方案
正如我在评论中提到的,您organizationInfoResponse
在 try-catch 块中为变量赋值,然后在函数结束时返回。如果它捕获错误,您的变量将不会获得分配给它的任何值,因此无法返回。您只需要在声明时为其分配一些值
推荐阅读
- c# - 全球秒表 WPF - 如何/为什么这不起作用
- angular - 无法导航到同级路由器
- javascript - 让 Microsoft Azure Web 应用程序聊天机器人使用电子邮件或 Twilio 从预设用户的表/列表中主动联系用户
- swisscomdev - 在 Swisscom CloudFoundry 上强制使用 HTTPS
- python - Gnuplot 伽玛函数
- r - 如何在 r 中创建特定的 3D 圆柱体并将它们绘制在地图中?
- nginx - 如何使用 Kong 服务 docker-compose 应用程序(react-flask)?
- asp.net-mvc - 将 JSON 发送到控制器 MVC 时出现 500 错误
- bson - BSON 阵列是异构的还是同质的?
- javascript - 在 WordPress 登录屏幕中实现 reCAPTCHA v3