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

Trả về response từ asynchronous call trong JavaScript

Async function không thể return trực tiếp giá trị cho caller đồng bộ. Có 2 pattern chính:

1. Callback-based

function myFunc(cb) {
  setTimeout(() => cb(100), 1000);
}
myFunc(a => console.log(a)); // 100 sau 1s

2. Promise-based (khuyên dùng)

new Promise(resolve => setTimeout(() => resolve(100), 1000))
  .then(console.log); // 100

3. Async/await (modern, readable)

async function fetchData() {
  const response = await fetch('/api/data');
  return response.json();
}

// Caller phải là async hoặc dùng .then()
fetchData().then(data => console.log(data));

Quy tắc vàng: Async function luôn trả về Promise. Caller phải dùng await (trong async function) hoặc .then() để lấy giá trị.