Languages
[Edit]
EN

JavaScript - check if function is async

6 points
Created by:
Marcin
19520

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;

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 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.

Look at below examples to see how to use them:

1. Constructor test example

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;

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, 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;

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