錯誤處理和控制流分支

回撥通常用於提供錯誤處理。這是控制流分支的一種形式,其中一些指令僅在發生錯誤時執行:

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 模式 )。