gpt4 book ai didi

javascript - 变量在使用 fetch 分配之前使用

转载 作者:行者123 更新时间:2023-12-04 07:36:01 24 4
gpt4 key购买 nike

Typescript 在我的函数的倒数第二行抛出以下错误:

Variable 'organizationInfoResponse' is used before being assigned.


我不太确定如何忽略这个问题,因为我正在分配 organizationInfoResponse在 fetch 中的 try catch 块内。你能在这里指出我正确的方向吗?
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 块中的变量,然后在函数末尾返回。如果它捕获错误,您的变量将不会获得任何分配给它的值,因此它无法返回。您只需要在声明时为其分配一些值

关于javascript - 变量在使用 fetch 分配之前使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67737336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com