Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Async Methods (Phương thức bất đồng bộ) trong JavaScript


Async function định nghĩa function bất đồng bộ. Trả về AsyncFunction object (thực chất là Promise).

Cú pháp

async function functionName([param[, param[, ... param]]]) {
  statements
}

Ví dụ: In kết quả sau 5 giây

<html>
  <body>
    <script>
      function displayFunction(num) {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve(num);
          }, 5000);
        });
      }
      
      async function add2(num) {
        const x = await displayFunction(7);  // Đợi 5s
        const y = await displayFunction(5);  // Đợi 5s nữa (tổng 10s) - sequential
        return num * x * y;
      }
      
      add2(15).then(result => {
        document.write("Multiplication Result (after 10 seconds): " + result);
        // 15 * 7 * 5 = 525
      });
    </script>
  </body>
</html>

Lưu ý quan trọng: Sequential vs Parallel

Ví dụ trên chạy sequential (tuần tự) - tổng 10 giây. Để chạy parallel (song song):

async function add2Parallel(num) {
  // Khởi tạo cả 2 promise cùng lúc
  const promiseX = displayFunction(7);
  const promiseY = displayFunction(5);
  
  // Đợi cả 2 (song song - chỉ 5 giây)
  const x = await promiseX;
  const y = await promiseY;
  
  return num * x * y;
}

// Hoặc dùng Promise.all
async function add2All(num) {
  const [x, y] = await Promise.all([
    displayFunction(7),
    displayFunction(5)
  ]);
  return num * x * y;
}

Async Function Characteristics

  • Luôn trả về Promise (tự wrap return value).
  • Cho phép dùng await bên trong.
  • await chỉ dùng được trong async function (trừ top-level module).
  • Error handling: try/catch thay vì .catch().

Error Handling

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch failed:', error);
    throw error; // re-throw hoặc return default
  }
}

Top-level await (ES2022)

Trong ES Module (<script type="module">), có thể dùng await ở top-level không cần wrap async function.