2

Given a variable, which is defined as follows:

const f = async function() {/* ... */};

How can I check if the variable f is of type async function ?

I already found this solution:

f.constructor.name === "AsyncFunction";

But the "f.constructor.name" is not compatible with IE11. Any other ideas ?

I know async functions does not work in IE11, ... but they work through babel compilation process. The idea is to find a way to detect async functions in an environment like node.js which would be compatible with IE11/babel for instance

Poyoman
  • 1,652
  • 1
  • 20
  • 28
  • 5
    Why do you need to do this? If your end goal is to be able to process both regular and promise-returning functions in the same way, `await Promise.resolve(f())` will do what you want. – AKX Nov 25 '19 at 17:10
  • 3
    This seems like a bad idea. There are functions that are not marked async but are still asynchronous and return a Promise. I would recommend you only perform introspection on the return type of a function. – Dan Nov 25 '19 at 17:12
  • If your problem is about compatibility, you can have another approach, like using some kind of [polyfill](https://www.npmjs.com/package/async-polyfill). In React, for example, you can use [React Polyfill](https://www.npmjs.com/package/react-app-polyfill) and get compatible from version IE9. – Luiz Fernando da Silva Nov 26 '19 at 11:16
  • Thank you for your comments. It looks like effectivelly, testing if a function is async is a bad idea, since with babel or other build tools, async functions are modified to be compatible with old browsers. @DanPantry has the good approach i think. There should not be different treatment of a function or an async function, then there is no reason to test one over an other variable type. Do you want to edit this comment as an answer ? – Poyoman Nov 26 '19 at 11:25

2 Answers2

0

This seems like a bad idea. There are plenty of functions out there that are effectively async (returning a Promise) but not flagged as such (perhaps they are transpiled down for browser support).

If you truly wanted to test if a function was async, it might be better to test if the return value has a .then property:

const maybeTask = f()
if ('then' in maybeTask) {
  maybeTask.then( .... )
}
Dan
  • 10,282
  • 2
  • 37
  • 64
-2

Instead of f.constructor.name, did you try f().constructor.name?

The former inspects f's constructor, whereas the latter will inspect the value returned by f(). If f is a async function, then f().constructor.name should return "Promise".

Not really sure if this is the best way to check for an async function, but thought it could help.