【发布时间】:2021-12-29 23:43:44
【问题描述】:
for (const item of filesForUpload) {
let resWithStatus: IResponseType;
try {
const res = await uploadFile(item);
resWithStatus = {
id: res?.id,
name: res?.name,
link: res?.link,
ext: res?.ext,
status: "SUCCESS",
};
} catch (err) {
resWithStatus = {
id: uuidv4(),
name: item.name,
link: URL.createObjectURL(item),
status: "FAILED",
};
console.log(err);
} finally {
const indexInUploadedImageState = newFileArray.findIndex((imageItem) => {
if (
resWithStatus.status === "FAILED" &&
imageItem.name === resWithStatus.name
)
return true;
if (
resWithStatus.status === "SUCCESS" &&
getFileNameWithoutExt(imageItem.name) === resWithStatus.name &&
getFileExt(imageItem.name) === resWithStatus.ext
)
return true;
return false;
});
console.log(resWithStatus); // Error occurs here
}
console.log(resWithStatus);
}
所以我用 TS 编写了这段代码,我在循环体内声明了一个带有 let 关键字的变量,类型为,但我仍然收到 错误:Variable is used before it is assigned。据我所知,这个变量 resWithStatus 不应该在所有 try、catch 和 finally 块中都可用,因为它在它们之外声明并在它们内部使用。我对 TS 很陌生,但知道它无法引用外部 resWithStatus 变量,我不明白为什么。
【问题讨论】:
-
你能提供一个有这个错误的工作示例吗?也许在代码沙盒或类似的地方。
-
@MarcoNisi 我可以给你上下文。整个循环位于异步函数内部。我们使用 uploadFile 方法执行一些异步任务,在循环内部我已经声明了变量,我尝试将其设置为
try或catch中的某个值,然后尝试在 finally 块内使用存储在该变量中的值因为变量本身是在 try、catch 和 finally 之外用 let 关键字声明的。但是当我尝试在 finally 块中访问该变量时,TS 会抛出错误Variable is being used before it is assigned但它会在任一块中分配一些东西。
标签: javascript typescript typescript-typings try-catch-finally