roomcayz
roomcayz

Reputation: 2564

TypeScript: cannot find name async/await

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.

Upvotes: 24

Views: 27527

Answers (1)

Nico
Nico

Reputation: 1202

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());
}

Upvotes: 35

Related Questions