javascript 関数がasyncを使用しているか判定する

javascript 関数がasyncを使用しているか判定する

javascriptで、関数がasyncを使用しているか判定するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

オブジェクトの最初の要素を削除

関数が「async」を使用しているか判定するには、「constructor.name」で結果が「AsyncFunction」であるかで判定します。

async function calc(x, y) {
  return x + y;
};

function calc2(x, y) {
  return x + y;
};

if (calc.constructor.name === 'AsyncFunction') {
  console.log('async');
} else {
  console.log('not async');
}

if (calc2.constructor.name === 'AsyncFunction') {
  console.log('async');
} else {
  console.log('not async');
}

実行結果

ちなみに「constructor.name」は通常の関数の場合は「Function」、クラスの場合は「クラス名」が取得できます。

function calc(x, y) {
  return x + y;
};

class Hoge {

  constructor() {}

}

const hoge = new Hoge();

console.log(calc.constructor.name); // Function

console.log(hoge.constructor.name); // Hoge

サンプルコード

以下は、
「 実行 」ボタンをクリックすると、アロー関数で記述された「async」の関数を実行して3秒待機後に「constructor.name」を表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-75 mx-auto" style="margin-top:200px">
    
    <h2><span class="badge badge-primary">結果</span></h2>

    <button type="button" onclick="hoge()" class="btn btn-raised btn-primary">
      実行
    </button>

  </div>

  <script>

    const hoge = () => {
      asyncFunc()
    }

    const asyncFunc = async () => {

      const sleep = () => {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve(1)
          }, 3000)
        })
      };

      await sleep();
      
      document.getElementsByClassName("badge")[0].textContent = asyncFunc.constructor.name;
      
    }    

  </script>
</body>

</html>

実行結果を確認すると、表示されているが確認できます。