Can I detect async/await available in browser? [duplicate]

社会主义新天地 提交于 2019-12-01 04:38:39

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!