0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript で非同期(async) / 同期(sync) の関数を判定

0
Posted at

やりたいこと

JavaScript で関数が非同期(async) か同期(sync) かを判定する。
非同期の場合には await で実行し、同期の場合にはそのまま実行する。

非同期関数の判定方法

fn が関数の場合、fn.constructor.name が 'AsyncFunction' かどうかで、関数が非同期かを判定することができる。

const isAsync = (fn) => {
    return fn?.constructor?.name === 'AsyncFunction';
};

実行例

const syncFunction = () => { console.log('sync'); };
const asyncFunction = async () => { console.log('async'); };

console.log(`isAsync(syncFunction): ${isAsync(syncFunction)}`);
console.log(`isAsync(asyncFunction): ${isAsync(asyncFunction)}`);
実行結果
isAsync(syncFunction): false
isAsync(asyncFunction): true

関数が非同期の場合に await で実行

関数が非同期の場合と同期の場合を isAsync() で判定することで、非同期の場合には await で関数を実行し、同期の場合には関数をそのまま実行することができる。

const autoAwait = async (fn) => {
    if (isAsync(fn)) {
        console.log(`${fn.constructor.name} is async`);
        await fn();
    } else {
        console.log(`${fn.constructor.name} is sync`);
        fn();
    }
};

autoAwait(syncFunction);
autoAwait(asyncFunction);
実行結果
Function is sync
sync
AsyncFunction is async
async
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?