【发布时间】:2011-11-23 15:01:09
【问题描述】:
哪种函数回调结构最适合在 Javascript 中使用,为什么?我已经看到这两个选项使用了很多。还有吗?
选项 A:
// DECLARATION
function funcA(required, success, error, options){
// if there is an error in your function return
// and run error function
if(errorHappens){ return error('an error') };
// if no error happened: run the success function
success('all good here is your var back', required);
}
。
// USAGE
funcA('this is required', function(result){
// all good, do something with the result :)
},
function(error){
// tell the user about the error
alert('error happened')
},{
optionalThing: ':-)'
});
选项 B:
// DECLARATION
function funcB(required, callback, options){
// if an error happens run the single callback with
// the err param populated and return
if(errorHappens){ return callback('an error') };
// if no error happened: run the callback with 'null'
// as the error param.
callback(null, 'this is a result');
}
.
// USAGE
funcB('this is required', function(err, result){
if(err){ return alert('error happened') };
// all good do something with the result :)
},{
optionalThing: ':-)'
}
【问题讨论】:
-
+1 看不出这是“没有建设性”的原因
标签: javascript function coding-style