我很难理解为什么我的代码不起作用,我需要一些帮助
onMount(async() => {
// download the media file
if (post.file_name) {
await fetch(`/api/file?fileName=${post.file_name}`, {
method: 'GET'
})
// convert the file into displayable image, video, or audio
.then(async res => {
const blob = await res.blob()
if (blob.type.includes('image')) {
mediaType = 'image'
let reader = new FileReader()
reader.readAsDataURL(blob);
reader.onload = (event) => {
media = event.target?.result
}
}
else if (blob.type.includes('video')) {
mediaType = 'video'
media = URL.createObjectURL(blob)
}
else if (blob.type.includes('audio')) {
mediaType = 'audio'
// TODO implement this
}
})
.catch(err => {
console.error(err);
})
}
然后我移动了该代码并在 .ts 文件中添加了日志记录,并从同一个 .svelte 文件调用它
.ts 文件
export function getFileRepresentation(fileName: string) {
let file: FileRepresentation = {
string: '',
type: undefined
}
fetch(`/api/file?fileName=${fileName}`, {
method: 'GET'
})
// convert the file into displayable image, video, or audio
.then(async res => {
const blob = await res.blob()
if (blob.type.includes('image')) {
file.type = 'image'
let reader = new FileReader()
reader.readAsDataURL(blob);
reader.onload = (event) => {
file.string = event.target?.result
console.log('in promise');
console.log(file.string); // DEBUGGING
}
}
else if (blob.type.includes('video')) {
file.type = 'video'
file.string = URL.createObjectURL(blob)
}
else if (blob.type.includes('audio')) {
file.type = 'audio'
// TODO implement this
}
})
.catch(err => {
console.error(err);
})
console.log('on return');
console.log(file.string); // DEBUGGING
return file
}
.svelte 文件
onMount(async() => {
if (post.file_name) {
const file = await getFileRepresentation(post.file_name)
media = file.string
mediaType = file.type
}
.ts 文件中的新代码不再有效。 console.logs 告诉我“返回时”首先被调用,file.string 是一个空字符串,然后“in promise”被调用第二个,其中的字符串具有正确的值。为什么此代码在此处与在 .svelte 文件中的工作方式不同?这都是客户端代码,所以我真的很困惑。
没有按预期工作的具体代码是第 53-59 行,但我注意到第 6-63 行工作,所以我不理解 FileReader.load() 的工作原理
编辑:用代码片段替换屏幕截图