简体   繁体   English

什么时候应该使用错误优先回调?

[英]When should an error-first callback be used?

There are two common ways of defining a function callback handlers: 定义函数回调处理程序有两种常用方法:

passing individual success and fail callback functions 传递个人成功和失败的回调函数

function doAsynchCall(on_success,on_fail){
    //do stuff
    if(condition === true){
        on_success(data);
    }
    else
    {
        on_fail(error);
    }
}

or handling the success/fail response within the same callback ( error-first, err-back, node-style ) 或者在同一个回调中处理成功/失败响应( 错误优先,错误返回,节点样式

function doAsynchCall(callback){
    //do stuff
    if(condition === true){
        callback(null,data);
    }
    else
    {
        callback(error,null);
    }
}

I've noticed that both versions get used, both work, and there is some degree of personal choice involved, but I'm certain there are some facts to support why one version may be preferred over other, or cases where the use warrants one over the other. 我注意到两个版本都得到了使用,两者都有效,并且涉及到某种程度的个人选择,但我确信有一些事实可以支持为什么一个版本可能比其他版本更受欢迎,或者使用哪个版本需要保证一个版本在另一个。

TL;DR; TL; DR;

What are the benefits and disadvantages of using a error-first callback? 使用错误优先回调有什么好处和坏处?

From the perspective of the user of the function, I would argue that the first way is better. 从功能的用户角度来看,我认为第一种方式更好。 Reason is that it leaves less work for the him/her and also allows for cleaner code. 原因是它为他/她留下了更少的工作,并且还允许更清晰的代码。 The user doesn't have to worry about determining if an error happened, he knows that his error handler will be called in case of an error. 用户不必担心确定是否发生错误,他知道在发生错误时将调用他的错误处理程序。

// Clean, modularized logic

function success() {
  // handle success
}

function error() {
  // handle error
}

doAsynchCall(success, error);

In the second way, by simply calling the function, the user doesn't know if an error has happened and essentially has to do the work of the if statement again to determine where to proceed. 在第二种方式中,通过简单地调用该函数,用户不知道,如果一个错误已经发生,基本上已经做的工作if 再次声明,以确定继续。

// does essentially the same stuff as doAsynchCall
function handler(error, data) {
  if (error !== null) {
    // handle error
  } else {
    // handle success
  }
}

doAsynchCall(handler):

However, the situation is basically inverted from the perspective of the function designer. 然而,从功能设计者的角度来看,情况基本上是颠倒的。 For him/her, it is easier to always pass the error as the first argument and and let the user determine how to handle and if to branch on an error. 对于他/她来说,总是将错误作为第一个参数传递并且让用户确定如何处理以及是否分支错误更容易。

function doAsynchCall(callback) {
    let data = getDataOrAnErrorHappens(); 
    callback(error, data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM