I'm using typescript@next
and I want to compile my code to es5
, but each time I'm using async
or await
keywords the compiler errors with that message:
Cannot find name 'await'.
Heres my libs: dom
, es2015
, es2016
, es2017
.
Code example:
let asyncFn = () => { return new Promise((resolve:Function)=>{resolve(2)}) } // should log `2` console.log(await asyncFn())
Such things are possible even with [email protected]
, I've tried it, but somehow I am unable to compile my code anyway.
Async - Await has been supported by TypeScript since version 1.7. 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.
An async/await will always return a Promise . Even if you omit the Promise keyword, the compiler will wrap the function in an immediately resolved Promise . This enables you to treat the return value of an async function as a Promise , which is quite useful when you need to resolve numerous asynchronous functions.
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.
You need to use your asyncFn inside a function marked as an 'async' function. For example:
async someAsyncCode() { let asyncFn = () => { return new Promise((resolve: Function) => { resolve(2); }); } // should log `2` console.log(await asyncFn()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With