Thenables in JavaScript phục vụ cho bài viết trên (ok)

Thenables in JavaScript

Apr 17, 2020

In JavaScript, a thenable is an object that has a then() functionarrow-up-right. All promises are thenables, but not all thenables are promises.

Many promise patterns, like chainingarrow-up-right and async/awaitarrow-up-right, work with any thenable. For example, you can use thenables in a promise chain:

// A thenable is an object with a `then()` function. The
// below thenable behaves like a promise that fulfills with
// the value `42` after 10ms.
const thenable = {
  then: function(onFulfilled) {
    setTimeout(() => onFulfilled(42), 10);
  }
};

Promise.resolve().
  then(() => thenable).
  then(v => {
    v; // 42
  });

You can also use thenables with await:

Thenables in the Wild

Many libraries implement thenables to enable async/await support. For example, Mongoose queriesarrow-up-right are thenables, although they also have an exec() function that returns a promise. Superagentarrow-up-right is a popular HTTP client that also uses thenables. However, neither Mongoose queries nor Superagent requests are actually promises.

Other libraries use promises directly. For example, Axios requests are promisesarrow-up-right in the sense that they are instanceof Promise.

You can convert an arbitrary thenable to a promise using Promise.resolve():


Async/await is the future of concurrency in JavaScript. "Mastering Async/Await" teaches you how to build frontend and backend apps using async/await in just a few hours. Get your copy!arrow-up-right

Last updated