函数回调结构的最佳实践是什么?

wil*_*age 6 javascript coding-style function

哪个函数回调结构最适合在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);
}
Run Code Online (Sandbox Code Playgroud)

.

// 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: ':-)'
});
Run Code Online (Sandbox Code Playgroud)


选项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');
}
Run Code Online (Sandbox Code Playgroud)

.

// USAGE
funcB('this is required', function(err, result){
  if(err){ return alert('error happened') };

  // all good do something with the result :)

},{
  optionalThing: ':-)'
}
Run Code Online (Sandbox Code Playgroud)

Ray*_*nos 6

对于node.js,这取决于环境

我个人建议您坚持使用回调作为最后一个参数

function doSomething(data, options, cb) {
  ...
  if (err) return cb(err);
  cb(null, result);
}

doSomething(data, { ... }, function (err, data) {
    if (err) throw err;
    ...
});
Run Code Online (Sandbox Code Playgroud)

主要是因为这是节点社区中使用的编码样式。如果您根本不与node.js进行交互,那么您应该使用与所交互的环境最通用的样式。

如果您的环境主要围绕jQuery,那么我只是$.Deferred从您的doSomething函数中返回一个对象

function doSomething(data, options) {
  return $.Deferred();
}

$.when(
  doSomething(data, { ... })
).then(
  function () { /* success */ },
  function () { /* error */ }
);
Run Code Online (Sandbox Code Playgroud)

编辑:

function doSomething(data, options, cb) {
  if (typeof options === "function") {
    cb = options;
    options = null;
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)