Eslint error with Array forEach iteration: Promise returned in function argument where a void return was expected

Viewed 693

I'm trying to write a function to do transformation for Files which are not throwing any exception like a method below. I'm seeing ESLint error - "Eslint: Promise returned in function argument where a void return was expected.". What can be done to fix this eslint?

Note we would skip the files which will throw Error. Those are appropriately logged though.

export async function createDataFromFiles(inputFiles: File[]): Promise<Data[]> {
        const result: Data = [];
    
        inputFiles.forEach(
            async (file) => {
                const imageData = new DataView(await file.arrayBuffer());
                const blobUrl = URL.createObjectURL(new Blob([imageData]));
                try {
                    const dimension = await getDimensionsFromImageUrl(blobUrl);
                    answer.push({ imageData, dimension });
                } finally {
                    URL.revokeObjectURL(blobUrl);
                }
            }
        );
    
        return Promise.all(answer);
    }
1 Answers

This is because of the signature of Array.forEach:

forEach(callbackfn: (value: undefined, index: number, array: undefined[]) => void): void.

The callbackFn has type void, but when using async the function implicitly returns a Promise.

You can avoid this warning by using an ordinary for...of loop:

export async function createDataFromFiles(inputFiles: File[]): Promise<Data[]> {
    const result: Data = [];

    for (const file of inputFiles) {
        const imageData = new DataView(await file.arrayBuffer());
        const blobUrl = URL.createObjectURL(new Blob([imageData]));
        try {
            const dimension = await getDimensionsFromImageUrl(blobUrl);
            answer.push({ imageData, dimension });
        } finally {
            URL.revokeObjectURL(blobUrl);
        }
    }

    return Promise.all(answer);
}
Related