Skip to content
javascript

Thenables in JavaScript

Mar 5, 2023Abhishek EH1 Min Read
Thenables in JavaScript

Thenable is a function or an object which has a then function, whereas a 'promise' is an object or function with a then method whose behavior conforms to this specification. Hence all promises are thenables and all thenables are not promises.

We can resolve thenables like a promise as shown below:

1const aThenable = {
2 then(onFulfilled, onRejected) {
3 onFulfilled(100)
4 },
5}
6aThenable.then(result => console.log("Resolved value:", result))

We can also use thenables with await syntax:

1const aThenable = {
2 then(onFulfilled, onRejected) {
3 onFulfilled(100)
4 },
5}
6const result = await aThenable
7console.log("Resolved value:", result)

Real-world example of thenables are mongoose queries. You can read more about how mongoose queries are not promises in the official documentation

We can convert a thenable to a Promise using the following code:

1const aThenable = {
2 then(onFulfilled, onRejected) {
3 onFulfilled(100)
4 },
5}
6const p1 = Promise.resolve(aThenable)
7p1 instanceof Promise // true

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2024 CodingDeft.Com