Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: cannot find name async/await

Tags:

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.

like image 230
Roomy Avatar asked Nov 03 '16 11:11

Roomy


People also ask

Does TypeScript have async await?

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.

What does await return TypeScript?

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.

Why we use await in TypeScript?

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.


1 Answers

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()); } 
like image 184
Nico Avatar answered Oct 17 '22 22:10

Nico