10

As title, how can I detect async/await es7 support in browser?

Is that possible?

Estus Flask
  • 179,509
  • 61
  • 360
  • 499
3142 maple
  • 787
  • 1
  • 8
  • 26

2 Answers2

14

As any other syntactic feature, it should be evaluated in order to be detected. Since eval can be restricted, this may be impossible when CSP is enabled:

let isAsync = true;

try {
  eval('async () => {}');
} catch (e) {
  if (e instanceof SyntaxError)
    isAsync = false;
  else
    throw e; // throws CSP error
}

If there's a chance that target browsers don't support a feature, the code should be transpiled.

The alternative that allows to avoid CSP restrictions on eval is to use external script to detect syntactic features, as described here.

Estus Flask
  • 179,509
  • 61
  • 360
  • 499
4

Currently there is no perfect solution for that, but it can be done using eval:

let isAsyncSupported;

try {
  isAsyncSupported = eval(`typeof Object.getPrototypeOf(async function() {}).constructor === 'function'`);
} catch (exception) {
  isAsyncSupported = false;
}

For more see:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Maciek Jurczyk
  • 485
  • 3
  • 7