简体   繁体   中英

Nested callbacks and exceptions handling in NodeJS

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?

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];
});

试用Node.js域核心模块: http : //nodejs.org/api/domain.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM