# 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()` function](https://masteringjs.io/tutorials/fundamentals/then). All promises are thenables, but not all thenables are promises.

Many promise patterns, like [chaining](https://masteringjs.io/tutorials/fundamentals/promise-chaining) and [async/await](https://masteringjs.io/tutorials/fundamentals/async-await), work with any thenable. For example, you can use thenables in a promise chain:

```javascript
// 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`:

```javascript
// 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);
  }
};

const v = await thenable;
v; // 42
```

### Thenables in the Wild <a href="#thenables-in-the-wild" id="thenables-in-the-wild"></a>

Many libraries implement thenables to enable async/await support. For example, [Mongoose queries](https://masteringjs.io/tutorials/mongoose/query) are thenables, although they also have an `exec()` function that returns a promise. [Superagent](https://visionmedia.github.io/superagent/) 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 promises](https://masteringjs.io/tutorials/axios/then) in the sense that they are `instanceof Promise`.

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

```javascript
// 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);
  }
};

const p = Promise.resolve(thenable);
p instanceof Promise; // true

const v = await p;
v; // 42
```

***

*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!*](http://asyncawait.net/?utm_source=masteringjs\&utm_campaign=asyncawait1)
