Borislav Hadzhiev
Sat Oct 30 2021·2 min read
Photo by Roberto Nickson
To check if a function is async, access the constructor.name
property on the
function and check if the value is equal to AsyncFunction
, e.g.
myFunction.constructor.name === 'AsyncFunction'
. If the equality check returns
true
, then the function is async.
const sum = async (a, b) => { return a + b; }; if (sum.constructor.name === 'AsyncFunction') { // 👇️ this runs console.log('✅ function is async'); } else { console.log('⛔️ function is NOT async'); }
When access on a function, the constructor
property returns:
Every async function in JavaScript is an AsyncFunction
object.
name
property on the constructor and check if the AsyncFunction
constructor was used to create the function.If the condition passes, then we have an async function.
If we access the name
property on a non-async function, the string
"Function"
is returned.
function example() {} console.log(example.constructor.name); // 👉️ "Function"
Different constructor functions are used to create async and non-async functions, so we can easily determine if a function is async.
// 👇️ non-async returns Promise function example() { return new Promise(resolve => { resolve(100); }); } console.log(example()); // 👉️ Promise {} console.log(example.constructor.name); // 👉️ "Function"
The example shows a non-async function, which returns a promise.
You can check if the return value of a function is a promise in the following way.
function example() { return new Promise(resolve => { resolve(100); }); } function isPromise(p) { if (typeof p === 'object' && typeof p.then === 'function') { return true; } return false; } console.log(isPromise(example())); // 👉️ true console.log(isPromise(() => {})); // 👉️ false
We check if the passed in value is an object and it contains a property named
then
that is of type function
.
then
property of type function that is not actually a promise.Most of the time you can't just call functions to check what their return value is because they might be mutating state, e.g. in a database.
However, if you could call the function without mutating any state, you can combine these 2 conditions.
if ( example.constructor.name === 'AsyncFunction' || (typeof example === 'function' && isPromise(example())) ) { console.log('✅ Function returns promise'); } else { console.log('⛔️ Function does NOT return promise'); }
Our if statement checks if the function is async or it returns a promise. If
either check passes, the if
block runs.