How to await and resolve actual data in loop

Issue

I’m looking to populate image-url and dimensions into the ImageData interface in typescript. The getDimensionsFromImageUrl is asynchronous call. How can I create ImageData array with no promises?

export interface ImageData {
    url: string;
    size: { width: number; height: number };
}

const images = [];
Array.from(inputFiles).forEach((file) => {
    const url = URL.createObjectURL(file);
    const size = getDimensionsFromImageUrl(url);
    images.push({ url, size });
});

await Promise.all(images);

Using await getDimensionsFromImageUrl(url); had eslint error
Promise returned in function argument where a void return was expected.
which I’m not able to resolve.

        Array.from(inputFiles).forEach(async (file) => {
            const url = URL.createObjectURL(file);
            const size = await getDimensionsFromImageUrl(url);
            images.push({ url, size });
        });

Solution

With promise.all must use .map instead of .forEach. The .map return a new list, in this case it is list of promise.

async function test() {
    const images = await Promise.all(Array.from(inputFiles).map(async (file): Promise<ImageData> => {
        const url = URL.createObjectURL(file);
        const size = await getDimensionsFromImageUrl(url);
        return { url, size };
    }));
    console.log(images);
}

Answered By – Trần Đức Huy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published