JS Tip of the Day: Thenable Objects

Thenable Objects
Version: ES2015
Level: Advanced

A thenable is any object that has a function property named then. The following is an example of a thenable object:

let myThenable = { then () {} };

Thenable objects in JavaScript are objects that are given special treatment when resolved by promises, effectively being seen as promise objects themselves. Rather than a thenable object becoming the resolved value, the then() method of the object is called and passed resolve and reject functions, much like you would specify in a then called from a promise. The thenable can then provide the promise chain a resolved or rejected value using these functions.

let normalObject = { normal: true };
let thenableObject = {
    then (resolve, reject) {
        resolve(1);
    }
};

Promise.resolve(normalObject)
    .then(value => console.log(value)); // { normal: true }

Promise.resolve(thenableObject)
    .then(value => console.log(value)); // 1

Thenables make it easy for built-in promises to work with alternative promise implementations as long as they use thenable objects.

More info: