How to know if a function is async?

后端 未结 8 803
别跟我提以往
别跟我提以往 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:43

    In case you're using NodeJS 10.x or later

    Use the native util function.

       util.types.isAsyncFunction(function foo() {});  // Returns false
       util.types.isAsyncFunction(async function foo() {});  // Returns true
    

    Do keep all the concerns in mind from above ansers though. A function that just returns by accident a promise, will return a false negative.

    And on top of that (from the docs):

    Note that this only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.

    But if you use async in NodeJS 10 and no transiplation. This is a nice solution.

提交回复
热议问题