简体   繁体   English

NodeJS中的嵌套回调和异常处理

[英]Nested callbacks and exceptions handling in NodeJS

I have came cross several answers and comments suggesting to avoid nested callbacks in NodeJS. 我遇到了一些答案和评论,建议避免在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 现在,假设我要在回调中编写的代码可能会导致异常,然后必须将catch和catch添加到代码中

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. 有人会建议使用step,async,wait-for,但是从性能的角度来看,我不认为它们是好的解决方案,因为它们仅提供了更简单的语法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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