Check if a Function returns a Promise in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

banner

Photo by Claude Piché

Check if a Function returns a Promise #

To check if a function returns a promise, check if the function is async or invoke it and check if the function returns an object that has a then property of type function. If either condition is met, the function returns a promise.

index.js
// ✅ Promise check function isPromise(p) { if (typeof p === 'object' && typeof p.then === 'function') { return true; } return false; } // ✅ Check if return value is promise function returnsPromise(f) { if ( f.constructor.name === 'AsyncFunction' || (typeof f === 'function' && isPromise(f())) ) { console.log('✅ Function returns promise'); return true; } console.log('⛔️ Function does NOT return promise'); return false; } // 👇️ Examples async function exampleAsync() {} function example() {} function examplePromise() { return new Promise(resolve => { resolve(42); }); } console.log(returnsPromise(exampleAsync)); // 👉️ true console.log(returnsPromise(example)); // 👉️ false console.log(returnsPromise(examplePromise)); // 👉️ true

The first function in the code snippet checks if the passed in value is a promise.

The second function takes another function as a parameter and checks if its return value is a promise.

The first condition in the if statement checks if the function is async.

Every async function returns a promise, so if the function is async, we immediately conclude that it returns a promise.

Our second condition checks if the passed in value is a function and invokes it, passing the result to the isPromise() function.

The only way to check if a non-async function returns a promise is to invoke it. Note that it might not be safe to invoke the function if it mutates state, e.g. writes to a database.

There are two ways to check if a function returns a promise:

  1. Check if the function is async - then it returns a promise 100% of the time
  2. Check if the function's return value is an object that has a property then of type function.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee