Home > Blockchain >  How does error handling work for async map inside an async function?
How does error handling work for async map inside an async function?

Time:07-04

I have successfully created a function that creates folders according to a directory.

However, when I have tried to convert the for of into a map() method using Promise.all(), the error was not handled the same.

import { readdir, mkdir } from 'fs/promises';

const copyUsingFor = async (target) => {
    try {
        const dir = await readdir(`./test`, { withFileTypes: true });
        for (const item of dir) {
            if (item.isDirectory()) {
                try {
                    await mkdir(`./${target}`);
                }
                catch (err) {
                    throw err;
                }
            }
        }
    }
    catch (err) {
        console.log(`desired err handling`);
        throw err;
    }
}

const copyUsingMap = async (target) => {
    try {
        const dir = await readdir(`./test`, { withFileTypes: true });
        Promise.all(
            dir.map(async item => {
                if (item.isDirectory()) {
                    try {
                        await mkdir(`./${target}`);
                    }
                    catch (err) {
                        throw err;
                    }
                }
            })
        )
    }
    catch (err) {
        throw err;
    }
}

copyUsingFor(`../`).catch(err => console.log(`An error occurred: ${err}`)) // <- Works.
copyUsingMap(`../`).catch(err => console.log(`An error occurred: ${err}`)) // <- Gives "triggerUncaughtException".

I am guessing it is because I have an async inside another, but could not figure out why it does not works the same.

Thanks!

CodePudding user response:

You are missing the await in front of Promise.all, that's all. Because of this, what happens inside the Promise.all is detached from the rest of your program flow.

Side note: catch (err) { throw err } is a no-op. You can get rid of the whole try/catch if you don't do anything other than rethrowing the error in it. It feels a bit like wrapping stuff in a call to a function x => x.

  • Related