Solve - then is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - then is not a function Error #

The "then is not a function" error occurs when the then() method is called on a value that is not a promise. To solve the error, convert the value to a promise before calling the method or make sure to only call the then() method on valid promises.

typeerror then is not a function

Here is an example of how the error occurs.

index.js
const obj = {}; // ⛔️ TypeError: then is not a function obj.then(value => { console.log(value); });

We called the Promise.then method on an object that isn't a promise and got the error back.

To solve the error, make sure to only call the then() method on valid promises.

index.js
const p1 = Promise.resolve('Hello'); p1.then(value => { console.log(value); // 👉️ Hello });

We used the Promise.resolve method to return a promise that resolves with the string Hello.

Alternatively, you can use the Promise() constructor and call the resolve function manually.

index.js
function sum(a, b) { return new Promise((resolve, reject) => { resolve(a + b); }); } sum(5, 5).then(result => { console.log(result); // 👉️ 10 });

The Promise constructor also returns a promise object, but for our purposes is a little more verbose than calling the Promise.resolve() method directly.

If the error persists, console.log the value you're calling the then() method on and make sure it's a promise.

Here is an example that checks if the value is a promise, before calling the then method.

index.js
const p1 = null; if (typeof p1 === 'object' && p1 !== null && 'then' in p1) { p1.then(value => { console.log(value); }); }

Our if condition uses the logical AND (&&) operator, so for the if block to run, all of the conditions have to be met.

We first check if the p1 variable stores a value with a type of object, because promises have a type of object.

Then we check if the variable is not equal to null. Unfortunately, if you check the type of null - console.log(typeof null), you will get an "object" value back, so we have to make sure the value is not null.

The last thing we check for is that the object contains the then property.

Then we know we can safely call the then method on the object.

Note that the then() method always returns a promise and functions that were marked as async always return a promise.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.