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

Khác biệt giữa Deferred, Promise và Future trong JavaScript

Future = thuật ngữ cũ, đồng nghĩa với Promise.

Promise

  • Đại diện cho **giá trị chưa biết** (sẽ có trong tương lai).
  • Proxy cho giá trị async — có 3 trạng thái: pending, fulfilled, rejected.
  • Immutable state: settled thì không đổi nữa.
  • Consumer: .then(), .catch(), .finally().

Deferred

  • Đại diện cho **công việc chưa xong** (computation).
  • Kế thừa/extends Promise (thường).
  • Có method resolve(), reject() để **tự resolve chính mình** (Promise thì resolve từ executor function).
  • Có thể coi là "Promise có thể tự điều khiển resolve/reject từ bên ngoài".

Mối quan hệ

Deferred tạo ra Promise. Deferred là "producer", Promise là "consumer view".

// jQuery Deferred pattern
const deferred = $.Deferred();
const promise = deferred.promise(); // consumer chỉ thấy promise

// Producer resolve khi xong
setTimeout(() => deferred.resolve('done'), 1000);

// Consumer
promise.then(val => console.log(val));

Modern JS: Chỉ dùng Promise (native). Deferred pattern ít dùng (jQuery legacy).