Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if function was defined with "async"

Tags:

javascript

I'm wondering if there's a way to determine if a function was defined using async function or async (...) => ... syntax?

I'm looking to implement the function isDefinedWithAsync where:

isDefinedWithAsync(async function() { return null; }) === true;
isDefinedWithAsync(function() { return null; }) === false;
isDefinedWithAsync(async () => null) === true;
isDefinedWithAsync(() => null) === false;

Is it possible to implement isDefinedWithAsync? And if so, how? Thanks!

like image 391
Gershom Maes Avatar asked Sep 04 '25 03:09

Gershom Maes


1 Answers

Yes,

Straight from the TC39 async/await Issues:

function isAsync(fn) {
   return fn.constructor.name === 'AsyncFunction';
}

Here's a snippet that checks your 2 async samples above and a 3rd non-async function:

function isAsync(fn) {
   return fn.constructor.name === 'AsyncFunction';
}

// async functions
const foo = async () => { }
async function bar () { } 

// non-async function
function baz () { } 

console.log(isAsync(foo)) // logs true
console.log(isAsync(bar)) // logs true
console.log(isAsync(baz)) // logs false

But as mentioned in the rest of the comments on that issue, you shouldn't differentiate, at least conceptually, between async functions and Promises since they behave the same.

Both can be await-ed/then-ed in the exact same way. An async marked function always implicitly returns a Promise.

like image 106
nicholaswmin Avatar answered Sep 05 '25 16:09

nicholaswmin