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

六眼飞鱼酱① 提交于 2019-12-01 02:54:02

问题


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

Is that possible?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/46126977/can-i-detect-async-await-available-in-browser

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