Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❀ đŸ’»
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

JavaScript - how to check / test if function is async / asynchronous ?

0 contributions
3 points

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

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more