Languages
[Edit]
EN

JavaScript - check if function is async

6 points
Created by:
Marcin
2453

In this article, we're going to have a look at how to check if function is async/asynchronous in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let func = async () => { /* some code here ... */ };
let isAsync = func.constructor && func.constructor.name === 'AsyncFunction';

console.log('is async: ' + (isAsync ? 'yes' : 'no'));

There are 2 ways to check if function is async:

  • by checking contructor type - we are able to know function type before is called,
  • by checking result type - when it is necessary to make some scanario after function is called - in most cases this approach is enought.

Look on below examples to see how to use it:

1. Constructor test example

In this section function is checked, if is asynchronous, before calling. In the below example to make test we use constructor name. 

// ONLINE-RUNNER:browser;

function isAsync(func) {
    if (func.constructor && func.constructor.name === 'AsyncFunction') {
        return true;
    }
    return false;
}

// Usage example:

let func1 = () => {
    console.log('Sync function called!');
};

let func2 = async () => {
    console.log('Async function called!');
};

console.log('func1 is ' + (isAsync(func1) ? 'asynchronous' : 'synchronous'));
console.log('func2 is ' + (isAsync(func2) ? 'asynchronous' : 'synchronous'));

2. Result test example

In this section function is checked, if is asynchronous, after calling by checking result type. In the below example to make test we use instanceof operator with function result.

Test should be made with following instruction that returns true or false:

functionResult instanceof Promise

Practical example:

// ONLINE-RUNNER:browser;

let func1 = () => {
    console.log('Sync function called!');
};

let func2 = async () => {
    console.log('Async function called!');
};

var result1 = func1();
var result2 = func2();

var func1IsAsync = result1 instanceof Promise;
var func2IsAsync = result2 instanceof Promise;

console.log('func1 is ' + (func1IsAsync ? 'asynchronous' : 'synchronous'));
console.log('func2 is ' + (func2IsAsync ? 'asynchronous' : 'synchronous'));

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.