TypeScript: cannot find name async/await

时光怂恿深爱的人放手 提交于 2021-02-06 14:53:08

问题


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 typescript@2.0.x, I've tried it, but somehow I am unable to compile my code anyway.


回答1:


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


来源:https://stackoverflow.com/questions/40400806/typescript-cannot-find-name-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!