EN
JavaScript - check if function is async
6
points
In this article, we're going to have a look at how to check if the function is async/asynchronous in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const func = async () => { /* ... */ };
if (func.constructor && func.constructor.name === 'AsyncFunction') {
console.log('Function is async.');
}
Â
There are 2 ways to check if the function is async:
- by checking constructor type - we are able to know function type before is called,
- by checking result type - when it is necessary to make some scenario after the function is called - in most cases this approach is enough.
Â
Checking constructor type
In this section, the function is checked, if is asynchronous, before calling. In the below example to make a test we use the constructor name.Â
// ONLINE-RUNNER:browser;
const isAsync = (func) => func.constructor && func.constructor.name === 'AsyncFunction';
// Usage example:
const func1 = () => {
console.log('Sync function called!');
};
const func2 = async () => {
console.log('Async function called!');
};
console.log('func1 is ' + (isAsync(func1) ? 'asynchronous' : 'synchronous'));
console.log('func2 is ' + (isAsync(func2) ? 'asynchronous' : 'synchronous'));
Â
Checking result type
In this section, the function is checked, if is asynchronous, after calling by checking the result type. In the below example to make a test we use instanceof
operator with a function result.
The test should be made with following instruction that returns true
or false
:
functionResult instanceof Promise
Practical example:
// ONLINE-RUNNER:browser;
const func1 = () => {
console.log('Sync function called!');
};
const func2 = async () => {
console.log('Async function called!');
};
const result1 = func1();
const result2 = func2();
console.log('func1 is ' + (result1 instanceof Promise ? 'asynchronous' : 'synchronous'));
console.log('func2 is ' + (result2 instanceof Promise ? 'asynchronous' : 'synchronous'));
Â