错误处理和控制流分支

回调通常用于提供错误处理。这是控制流分支的一种形式,其中一些指令仅在发生错误时执行:

const expected = true;

function compare(actual, success, failure) {
  if (actual === expected) {
    success();
  } else {
    failure();
  }
}

function onSuccess() {
  console.log('Value was expected');
}

function onFailure() {
  console.log('Value was unexpected/exceptional');
}

compare(true, onSuccess, onFailure);
compare(false, onSuccess, onFailure);

// Outputs:
//   "Value was expected"
//   "Value was unexpected/exceptional"

上面 compare() 中的代码执行有两个可能的分支:success 当预期值和实际值相同时,error 当它们不同时。当控制流应该在一些异步指令之后分支时,这尤其有用:

function compareAsync(actual, success, failure) {
  setTimeout(function () {
    compare(actual, success, failure)
  }, 1000);
}

compareAsync(true, onSuccess, onFailure);
compareAsync(false, onSuccess, onFailure);
console.log('Doing something else');

// Outputs:
//   "Doing something else"
//   "Value was expected"
//   "Value was unexpected/exceptional"

应该注意,多个回调不必相互排斥 - 可以调用这两种方法。类似地,compare() 可以用可选的回调编写(通过使用 noop 作为默认值 - 参见 Null Object 模式 )。