繁体   English   中英

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

[英]Nested callbacks and exceptions handling in NodeJS

我遇到了一些答案和评论,建议避免在NodeJS中嵌套嵌套的回调。 我相信这背后有很强的观点,但我无法正确理解!

假设我有以下代码

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

现在,假设我要在回调中编写的代码可能会导致异常,然后必须将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}

    }
);

现在,我不仅具有嵌套的回调,而且还具有异常处理的回调,这会增加内存开销!

有人会建议使用step,async,wait-for,但是从性能的角度来看,我不认为它们是好的解决方案,因为它们仅提供了更简单的语法。 如果我错了纠正我。

有什么办法可以避免这种问题? 提高回调嵌套代码的性能?

承诺会自动传播异步和同步错误

这意味着什么?

这表示希望正确传播错误的回调代码的代码:

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

可以替换为:

// 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