问题
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