Thenable 对象

js/thenable2026-10-29 11:03:47

在 Promise 成为 JavaScript 语言的一部分之前,JavaScript 生态系统已经有了多种 Promise 实现。尽管它们在内部的表示方式不同,但至少所有类 Promise 的对象都实现了 Thenable 接口。

Thenable 对象

Thenable 对象 实现了 .then() 方法,该方法被调用时需要传入两个回调函数,一个用于 Promise 被兑现时调用,一个用于 Promise 被拒绝时调用。Promise 也是 thenable 对象。

const thenable = {
  then: function(onFulfilled, onRejected) {
    // 模拟异步操作
    setTimeout(() => {
      onFulfilled("Success!");
    }, 1000);
  }
};

thenable.then(
  result => console.log(result), // 输出: Success!
  error => console.error(error)
);

Thenable 对象和 Promise 的区别

const thenable = {
  then: function(onFulfilled, onRejected) {
    setTimeout(() => {
      onFulfilled("Success!");
    }, 1000);
  }
};

thenable.then(
  result => console.log(result), // 输出: Success!
  error => console.error(error)
);
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 1000);
});

promise.then(
  result => console.log(result), // 输出: Success!
  error => console.error(error)
);

Thenable 对象没有内置的状态管理机制。每次调用 then 都会重新执行内部逻辑代码,然后再执行 onFulfilled 或 onRejected。调用 then 后不会返回另一个 Thenable 对象。

new Promise() 传入的函数只会执行一次。Promise 每次调用 then 后会根据状态决定何时执行 onFulfilled 或 onRejected。调用 then 后会返回另一个待定的 Promise 对象。

使用 Thenable 对象替代 Promise

为了与现有的 Promise 实现进行交互,JavaScript 语言允许在 Promise 的位置使用 thenable 对象。例如,Promise.resolve 方法不仅可以解析 Promise 对象,还可以追踪 thenable 对象。

const aThenable = {
  then(onFulfilled, onRejected) {
    onFulfilled({
      // thenable 对象被兑现为另一个 thenable 对象
      then(onFulfilled, onRejected) {
        onFulfilled(42);
      },
    });
  },
};

Promise.resolve(aThenable); // 一个兑现值为 42 的 Promise

参考

Thenable
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenable

本页目录