Home > Software engineering >  How to perform cleanup of individually allocated things cleanly?
How to perform cleanup of individually allocated things cleanly?

Time:08-29

Given is the following function:

function createDir(): { path: string, x: number, y: number };

If the function is executed multiple times in a row we have this:

const { path: path0 } = createDir();
/* ... do something here */
const { path: path1 } = createDir();
/* ... do something ELSE here */
const { path: path2 } = createDir();
/* ... do something completely else here */
const { path: path3 } = createDir();
/* ... and here is another code block */ 

What is the most TypeScriptish way to remove all directories at the end, even if one of the functions fails in between? It seems I have to use a try/catch here but how do I perform a cleanup in the finally block of a try/catch?

This solution looks unnecessarily complicated to me:

let cleanup: string[] = [];
try {
    const { path: path0 } = createDir();
    /* ... do something here */
    cleanup.push(path0);
    const { path: path1 } = createDir();
    /* ... do something ELSE here */
    cleanup.push(path1);
    const { path: path2 } = createDir();
    /* ... do something completely else here */
    cleanup.push(path2);
    const { path: path3 } = createDir();
    /* ... and here is another code block */
    cleanup.push(path3);
} finally {
    for (const path of cleanup) {
        fs.rmSync(path, { recursive: true });
    }
}

CodePudding user response:

This solution looks unnecessarily complicated to me

I don't think it gets a lot more elegant, it's one of those cumbersome things by nature. You could have a function to do both the creation and the addition to the array. Also, don't forget to catch and either handle or suppress errors from the rmSync call at the end, so a failure on one doesn't prevent removing the others.

const cleanup: string[] = [];
const create = () => {
    const { path } = createDir();
    cleanup.push(path);
    return path;
};
try {
    const path0 = create();
    /* ... do something here */
    const path1 = create();
    /* ... do something ELSE here */
    const path2 = create();
    /* ... do something completely else here */
    const path3 = create();
    /* ... and here is another code block */
} finally {
    for (const path of cleanup) {
        try {
            fs.rmSync(path, { recursive: true });
        } catch (error) {
            console.error(error); // or something
        }
    }
}
  • Related