[Solved] How does one elegantly provide try-catch functionality to functions and methods which are listed within an array and are about to be executed/invoked?


The functions are not being executed “automatically,” they’re being executed because you’re explicitly calling them:

const arr = [
    { 'Some text': this.f('a') },
    //             ^^^^^^^^^^^−−−−−−−−−−−−−− here
    { 'Some other text': this.f('b') }
    //                   ^^^^^^^^^^^−−−−−−−− and here
]

The result of the above is an array with two objects in it, where the first object has a property called Some text whose value is the result of having called this.f('a') and the second object has a property called Some other text whose value is the result of having called this.f('b').

If you wanted to delay those calls until some later time, you’d need to wrap them in functions:

const arr = [
    { 'Some text': () => this.f('a') },
    //             ^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−− wrapper function
    { 'Some other text': () => this.f('b') }
    //                   ^^^^^^^^^^^^^^^^^−−−−−−−− wrapper function
]

Later, you’d call them like this:

arr[0]["Some text"]();
arr[0]["Some other tex"]();

or similar.

If you want to call them later wrapped in try/catch blocks, you could do it like this:

for (const obj of arr) {
    for (const fn of Object.values(obj)) {
        try {
            fn();
        } catch (e) {
            // ...
        }
    }
}

…or the equivalent with forEach:

arr.forEach(obj => {
    Object.values(obj).forEach(fn => {
        try {
            fn();
        } catch (e) {
            // ...
        }
    });
});

In another comment you’ve said:

how would you replace the function with function result?

I suspect you want something like this:

const arr = [
    { 'Some text': () => this.f('a') },
    { 'Some other text': () => this.f('b') }
].map(obj => {
    return Object.fromEntries(Object.entries(obj).map(([key, value]) => {
        try {
            value = value();
        } catch (e) {
            // ...presumably do something with the fact it failed...
        }
        return [key, value];
    }));
});

The result of the above is that arr has objects with the same keys as the initial object literal, but with the values being the result of calling the functions (or whatever you write to value in the catch block).

See:

6

solved How does one elegantly provide try-catch functionality to functions and methods which are listed within an array and are about to be executed/invoked?