How to know if a function is async?

后端 未结 8 801
别跟我提以往
别跟我提以往 2020-12-01 00:55

I have to pass a function to another function, and execute it as a callback. The problem is that sometimes this function is async, like:

async function() {
          


        
8条回答
  •  遥遥无期
    2020-12-01 01:37

    Both @rnd, and @estus are correct.

    But to answer the question with an actual working solution here you go

    function isAsync (func) {
        const string = func.toString().trim();
    
        return !!(
            // native
            string.match(/^async /) ||
            // babel (this may change, but hey...)
            string.match(/return _ref[^\.]*\.apply/)
            // insert your other dirty transpiler check
    
            // there are other more complex situations that maybe require you to check the return line for a *promise*
        );
    }
    

    This is a very valid question, and I'm upset that someone down voted him. The main usecase for this type of checking is for a library/framework/decorators.

    These are early days, and we shouldn't downvote VALID questions.

提交回复
热议问题