1

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!

  • Sorry, your `copyUsingMap` function does not have any calls to `map()`, it does have to `forEach()`. Can you edit the questions and clarify if your problem is with `map` or `forEach`? – Renato Jul 03 '22 at 11:23
  • I also don't see any calls to `Promise.all()`. – Renato Jul 03 '22 at 11:24
  • I'm sorry, it was just another test I thought would help me figure it out that I accidentally copied. Now it's fixed, thanks. –  Jul 03 '22 at 11:28

1 Answers1

1

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.

CherryDT
  • 25,571
  • 5
  • 49
  • 74
  • Thanks, that helped a lot. About the catch with the throw, it does not generate a message at all without it. –  Jul 03 '22 at 12:59
  • That doesn't sound right. A `try { xyz() } catch (err) { throw err }` does nothing different from just `xyz()`. [You can see it in action here](https://jsfiddle.net/3m0zk1q6/). – CherryDT Jul 04 '22 at 00:46