【问题标题】:Nested callbacks and exceptions handling in NodeJSNodeJS 中的嵌套回调和异常处理
【发布时间】:2014-08-01 04:30:08
【问题描述】:

我遇到了几个答案,并且 cmets 建议避免在 NodeJS 中嵌套回调。我相信这背后有一个强烈的观点,但我无法正确理解!

假设我有以下代码

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

现在假设我在回调中编写的代码可能会导致异常,然后必须将 try 和 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,但我不认为从性能角度来看它们是好的解决方案,因为它们只提供更简单的语法,仅此而已。如果我错了,请纠正我。

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

【问题讨论】:

  • Promise 是解决这个问题的方法。

标签: javascript node.js asynchronous callback


【解决方案1】:

Promises 自动传播异步和同步错误

这是什么意思?

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      相关资源
      最近更新 更多