I have an array of image paths, and I need to convert it to array of blobs:
I use a function:
const pathToBlob = async (url: string) => {
return await fetch(url).then(r => r.blob())
.then(blobFile => new File([blobFile],
"fileNameGoesHere", {type: "image/png"})
)
}
Then I'm trying to use it:
let blobs:any = []
if (vehicle.images) {
for (let i of vehicle.images) {
//@ts-ignore (cant type i into loop)
const file = pathToBlob(process.env.REACT_APP_API_URL i.img)
blobs=[blobs,...file] // error
console.log(file) // [[Prototype]]: Promise [[PromiseState]]: "fulfilled [[PromiseResult]]: File
}
console.log(blobs)
}
But I'm recieving a Promise with:
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: File
Otherwise Into function (if I refactor to const file = await....
console.log(file)
)
I'm getting a ready blob.
CodePudding user response:
Try this, I added an async iife
to get an async context since I don't from where you are running this. This is needed to be able to use await
.
const pathToBlob = async (url: string) => {
const blob = await fetch(url).then(r => r.blob());
return new File([blob], "fileNameGoesHere", { type: "image/png" });
}
(async () => {
const blobs: Array<File> = await Promise.all(
vehicle.images.map(async (image: any) => {
return pathToBlob(process.env.REACT_APP_API_URL image.img);
}),
);
console.log({ blobs });
})();