I'm having a hard time understanding why my code doesn't work and I need some help
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);
})
}
I then moved that code and added logging to it in a .ts file and call it from the same .svelte file
.ts file
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 file
onMount(async() => {
if (post.file_name) {
const file = await getFileRepresentation(post.file_name)
media = file.string
mediaType = file.type
}
The new code in the .ts file no longer works. The console.logs show me that the 'on return' one is called first, with file.string being an empty string, and then 'in promise' one being called second with the string having the correct value in it. Why is this code working differently here than in the .svelte file? It's all client side code so I'm really confused.
The specific code that doesn't work as expected is lines 53-59, but I noticed that lines 6-63 work, so there's something I'm not understanding with how FileReader.load() works
Edit: replaced screenshots with code snippets