Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async functions are only available when targeting ECMAScript 2015 or higher

I want to be able to use the async keyword but I want my typescript to compile into es5 code so that my code can run in the average persons browser. I get this error when I try to use async in visual studio code.

Async functions are only available when targeting ECMAScript 2015 or higher.

I thought that targeting es6 means that the output javascript from compiling the typescript will be es6, and es6 doesn't work on most browsers yet?

Here is my tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "lib": ["es2015", "dom"],
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "outDir":"js/app/",
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
    "exclude": [
    "node_modules",
    "app/test"
  ]
}

I was wondering if the lib field might make it work because it says "es2015" but it doesn't.

I'm also thinking maybe the core-js shim makes async available but I only include that shim in my index.html like this:

<script src="node_modules/core-js/client/shim.min.js"></script>

So I don't think it's making async available at compile time. Is there a better way to import core-js?

How do I make async usable but also not have my code be unable to run on most browsers?

like image 678
BeniaminoBaggins Avatar asked Nov 28 '16 04:11

BeniaminoBaggins


1 Answers

ECMAScript6 is supported in most major browsers.

As stated in the comments on this answer by @loganfsmyth,

Just keep in mind that "most major browsers" could still only cover a tiny percentage of your user base.

Firefox

Chrome

From Safari's website,

ES6 The ECMAScript 2015 standard, also known as ES6, is completely supported, bringing this major JavaScript evolution to Safari on macOS and iOS.

You are going to have to change,

"target": "es5",

To

"target": "es6",

TypeScript 1.7 async/await support in ES6 targets (Node v4+) TypeScript now supports asynchronous functions for engines that have native support for ES6 generators, e.g. Node v4 and above. Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.

like image 181
wuno Avatar answered Oct 26 '22 23:10

wuno