typescript 如何通过从promise中获取blob来解决将blob添加到数组中的问题?

kninwzqo  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(269)

我有一个图像路径数组,需要将其转换为blob数组:
我使用一个函数:

const pathToBlob = async (url: string) => {
    return await fetch(url).then(r => r.blob())
        .then(blobFile => new File([blobFile],
            "fileNameGoesHere", {type: "image/png"})
        )
}

然后我试着用它:

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)
}

但我收到的承诺是:

[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: File

否则Into函数(如果我重构为const file = await....console.log(file))我得到了一个就绪的blob。

ippsafx7

ippsafx71#

试试这个,我添加了一个async iife来获得一个async上下文,因为我没有从你运行这个的地方。这是能够使用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 }); 
})();

相关问题