0

I am using async-await and handling errors through try-catch when an error is thrown in. method3() it is not being caught in method1(). however, if I removed async in the. method2() foreach I am able to catch the error in method1()! But I cannot use await if I remove async in foreach I cannot use await! Is there a way to solve this

class A {
    async method1(A, B) {
        return new Promise(async (resolve, reject) => {
            try {
                await this.method2(A, B);

            } catch (error) {
                console.log(error, "error")

            };
        });

    }
    async  method2(A, B, C) {

        await somethingelsecalled();
        Array.forEach(async (segment, index) => {
            result = await somethingcalled()
            this.method3(result);

        });
    }

    method3() {
        throw "error";
    }
}

1 Answers1

1

Replacing the foreach with for of loop solved the problem

    class A {
        async method1(A, B) {
            return new Promise(async (resolve, reject) => {
                try {
                    await this.method2(A, B);

                } catch (error) {
                    console.log(error, "error")

                };
            });

        }
        async  method2(A, B, C) {

            await somethingelsecalled();
             for (const [index, segment] of Array.entries()) {
                result = await somethingcalled()
                this.method3(result);

            });
        }

        method3() {
            throw "error";
        }
    }