嵌套的回调和例外处理的NodeJS [英] Nested callbacks and exceptions handling in NodeJS
问题描述
我已经来到跨几个答案和意见建议,以避免嵌套的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!
让我们假设我有以下的code
Let's assume that I have the following code
module1.func1(
function(){
//some code
module2.func2(
function(){
//some code
module3.func3(etc....)
}
);
}
);
现在让我们假设code我会在回调写会引起那么一个异常尝试和catch必须添加到code
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.
有什么办法避免这样的问题呢?改善回调-nested- code的表现呢?
Is there any way to avoid such problem? to improve performance of callbacks-nested-code?
推荐答案
承诺自动传播异步和同步错误
Promises automatically propagate both asynchronous and synchronous errors
这是什么意思?
这意味着code的回调code愿望的正确传播错误:
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);
}
可以替换为:
// 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];
});
这篇关于嵌套的回调和例外处理的NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!