Languages
[Edit]
EN

JavaScript - check if function is async

6 points
Created by:
Brandy-Mccabe
724

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'));

 

Alternative titles

  1. JavaScript - test if function is async
  2. JavaScript - check if function is asynchronous
  3. JavaScript - test if function is asynchronous
  4. JavaScript - check if method is asynchronous
  5. JavaScript - check if method is async
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join