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

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com