TypeScript:找不到名称异步/等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40400806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:59:20  来源:igfitidea点击:

TypeScript: cannot find name async/await

typescriptasync-await

提问by Roomy

I'm using typescript@nextand I want to compile my code to es5, but each time I'm using asyncor awaitkeywords the compiler errors with that message:

我正在使用typescript@next并且我想将我的代码编译为es5,但是每次我使用asyncorawait关键字时都会出现带有该消息的编译器错误:

Cannot find name 'await'.

Heres my libs: dom, es2015, es2016, es2017.

继承人我的库: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.

即使使用[email protected],这样的事情也是可能的,我已经尝试过了,但无论如何我都无法编译我的代码。

回答by Nico

You need to use your asyncFn inside a function marked as an 'async' function. For example:

您需要在标记为“异步”函数的函数中使用 asyncFn。例如:

async someAsyncCode() {
    let asyncFn = () => {
        return new Promise((resolve: Function) => { resolve(2); });
    }
    // should log `2`
    console.log(await asyncFn());
}