Introduction: callbacks

// JavaScript 有許多函式都是異步
function loadScript(src) {
  let script = document.createElement('script');
  script.src = src;
  document.head.append(script);
}

// loads and executes the script
loadScript('/my/script.js');

// 新增 js 檔到 HTML 完成這行指令需要時間,js 會繼續執行其他程式嗎
loadScript('/my/script.js');
// the code below loadScript doesn't wait for the script loading to finish
// ...

// 因為加載腳本需要時間,如果立即使用腳本內的程式碼會出現錯誤,我們不知道何時腳本才加載完畢
loadScript('/my/script.js'); // the script has "function newFunction() {…}"
newFunction(); // no such function!

// 新增 callback 函式,當腳本加載完成後執行
function loadScript(src, callback) {
  let script = document.createElement('script');
  script.src = src;

  script.onload = () => callback(script);

  document.head.append(script);
}

// 如果要使用腳本內程式碼,要加在 callback 裡。
loadScript('/my/script.js', function() {
  // the callback runs after the script is loaded
  newFunction(); // so now it works
  ...
});

// 當動作執行完,執行第二個參數(函式)
function loadScript(src, callback) {
  let script = document.createElement('script');
  script.src = src;
  script.onload = () => callback(script);
  document.head.append(script);
}

loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js', script => {
  alert(`Cool, the ${script.src} is loaded`);
  alert( _ ); // function declared in the loaded script
});

Callback in callback

// 如何依序加載腳本,把加載第 2 個腳本放到 callback,加載完第 1 個會加載第 2 個。
loadScript('/my/script.js', function(script) {

  alert(`Cool, the ${script.src} is loaded, let's load one more`);

  loadScript('/my/script2.js', function(script) {
    alert(`Cool, the second script is loaded`);
  });

});

// 要加載一些腳本可以,若要加載很多腳本不適合
loadScript('/my/script.js', function(script) {

  loadScript('/my/script2.js', function(script) {

    loadScript('/my/script3.js', function(script) {
      // ...continue after all scripts are loaded
    });

  })

});

Handling errors

// 加載可能會失敗,因此要追蹤錯誤
function loadScript(src, callback) {
  let script = document.createElement('script');
  script.src = src;

  script.onload = () => callback(null, script);
  script.onerror = () => callback(new Error(`Script load error for ${src}`));

  document.head.append(script);
}

// 使用
loadScript('/my/script.js', function(error, script) {
  if (error) {
    // handle error
  } else {
    // script loaded successfully
  }
});

Pyramid of Doom

// 當我們加載很多腳本
loadScript('1.js', function(error, script) {

  if (error) {
    handleError(error);
  } else {
    // ...
    loadScript('2.js', function(error, script) {
      if (error) {
        handleError(error);
      } else {
        // ...
        loadScript('3.js', function(error, script) {
          if (error) {
            handleError(error);
          } else {
            // ...continue after all scripts are loaded (*)
          }
        });

      }
    })
  }
});

// 巢狀函式變多,程式碼越深層,越難維護,被稱為回調地獄
// 透過每一個動作編寫一個獨立函式解決這個問題,但程式碼很分散可讀性差,step* 都是單獨使用,
// 為了避免回調地獄產生的函數,只使用一次,造成函數命名混亂。
loadScript('1.js', step1);

function step1(error, script) {
  if (error) {
    handleError(error);
  } else {
    // ...
    loadScript('2.js', step2);
  }
}

function step2(error, script) {
  if (error) {
    handleError(error);
  } else {
    // ...
    loadScript('3.js', step3);
  }
}

function step3(error, script) {
  if (error) {
    handleError(error);
  } else {
    // ...continue after all scripts are loaded (*)
  }
};

Last updated