24

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.

4
  • Please post your code. Is your function marked with async? Commented Nov 3, 2016 at 13:18
  • no, it's not, but I don't need to mark my scope as 'async', right? afaik that's only syntastic sugar for Promise Commented Nov 3, 2016 at 13:42
  • 2
    Read the documentation: "Asynchronous functions are prefixed with the async keyword" Commented Nov 3, 2016 at 13:45
  • 2
    @Roomy: async and await are a pair of keywords. You can't use await unless it's within an async scope. Commented Nov 3, 2016 at 15:35

1 Answer 1

35

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Pretty shocking that even the dumb TypeScript compiler can't give a better error message. Something like await cannot be used outside of an async scope would have been fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.