Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การส่งฟังก์ชันเป็น Callback ใน JavaScript

Callback Function คือฟังก์ชันที่ถูกส่งผ่าน Argument ให้ฟังก์ชันอื่น แล้วฟังก์ชันรับจะเรียก (Invoke) Callback นั้นภายหลัง ใช้สำหรับ Asynchronous Operations, Event Handling, Array Methods

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Callback Function</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>ส่งฟังก์ชันเป็น Callback ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อส่ง add2() เป็น Callback ให้ multiply9()</h3>
  <script>
    const resEle = document.querySelector(".result");
    
    function add2(a) {
      return a + 2;
    }
    
    function multiply9(fn, num) {
      return fn(num) * 9;
    }
    
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = `ผลลัพธ์ = ${multiply9(add2, 12)}`; // (12+2)*9 = 126
    });
  </script>
</body>
</html>

Callback Patterns


// 1. Synchronous Callback (Array Methods)
[1,2,3].map(x => x * 2);
[1,2,3].filter(x => x > 1);
[1,2,3].forEach(x => console.log(x));

// 2. Asynchronous Callback (Old Style)
function fetchData(callback) {
  setTimeout(() => callback("Data loaded"), 1000);
}
fetchData(data => console.log(data));

// 3. Error-first Callback (Node.js Style)
function readFile(path, callback) {
  fs.readFile(path, (err, data) => {
    if (err) return callback(err);
    callback(null, data);
  });
}

// 4. Higher-Order Function (Return Function)
function multiplier(factor) {
  return function(num) {
    return num * factor;
  };
}
const double = multiplier(2);
double(5); // 10

Callback Hell และการแก้ไข


// ❌ Callback Hell (Pyramid of Doom)
getUser(id, user => {
  getPosts(user.id, posts => {
    getComments(posts[0].id, comments => {
      console.log(comments);
    });
  });
});

// ✅ Promises
getUser(id)
  .then(user => getPosts(user.id))
  .then(posts => getComments(posts[0].id))
  .then(comments => console.log(comments));

// ✅ Async/Await (Modern)
const user = await getUser(id);
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);

ผลลัพธ์

ผลลัพธ์ = 126 (คำนวณ: add2(12) = 14, 14 * 9 = 126)