Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Is that possible?

like image 567
3142 maple Avatar asked Sep 09 '17 04:09

3142 maple


People also ask

Is async await supported in browsers?

According to the release notes, Safari 10.1 added support for ECMAScript 2016 and ECMAScript 2017 in Safari for macOS and iOS, including support for async and await.

Can one async function have multiple awaits?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Is async await concurrent?

It is concurrent, in the sense that many outstanding asychronous operations may be in progress at any time. It may or may not be multithreaded. By default, await will schedule the continuation back to the "current execution context".

Does async await block execution?

await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have an effect on it.


2 Answers

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.

like image 103
Estus Flask Avatar answered Oct 27 '22 05:10

Estus Flask


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

like image 29
Maciek Jurczyk Avatar answered Oct 27 '22 06:10

Maciek Jurczyk