Nested callbacks and exceptions handling in NodeJS

2019-06-10 22:56发布

I have came cross several answers and comments suggesting to avoid nested callbacks in NodeJS. I believe there is a strong point of view behind that but I can not get it properly!

Let's assume that I have the following code

module1.func1(
    function(){
        //some code
        module2.func2(
            function(){
                //some code
                module3.func3(etc....)
            }
        );
    }
);

Now let's assume that the code I would write in the callback may cause an exception then try and catch must be added to the code

module1.func1(
    function(){
        try{
            //some code
            module2.func2(
                function(){
                    try {
                        //some code
                        module3.func3(etc....)
                    } catch (ex){//handle exception}
                }
            );
        } catch(e){//handle exception}

    }
);

Now, I'm not only having nested callbacks but also with exceptions-handled callbacks which add more overhead on memory!

Some would suggest using step, async, wait-for but I don't believe they are good solutions from performance perspective as they only provide simpler syntax and that's it. Correct me if I'm wrong.

Is there any way to avoid such problem? to improve performance of callbacks-nested-code?

2条回答
做个烂人
2楼-- · 2019-06-10 23:46

Promises automatically propagate both asynchronous and synchronous errors

What does that mean?

It means code that callback code that wishes to propagate errors properly:

try {
    doStuff1(function(err, value) {
        if (err) return caller(err);
        try {
            doStuff2(value, function(err, value2) {
                if (err) return caller(err);
                try {
                    doStuff3(value2, function(err, value3) {
                        if (err) return caller(err);
                        caller(null, [value3]);
                    });
                } catch(e) {
                    caller(e);
                }
            });
        } catch (e) {
            caller(e);
        }
    })
} catch (e) {
    caller(e);
}

Can be replaced with:

// Returning a value normally to the caller
return doStuff1()
.then(function(value) {
    return doStuff2(value);
})
.then(function(value2) {
    return doStuff3(value2);
})
.then(function(value3) {
    return [value3];
});
查看更多
该账号已被封号
3楼-- · 2019-06-10 23:50

Try Node.js Domain core module: http://nodejs.org/api/domain.html

查看更多
登录 后发表回答