本文介绍了TypeScript:找不到名称异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 typescript @ next ,我想将我的代码编译为 es5 ,但是每次我使用 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'.

这里有我的库: dom es2015 es2016 es2017 .

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

代码示例:

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

即使使用 [email protected] ,也可以实现某些功能,但我还是尝试过,但是无论如何我还是无法编译我的代码.

Such things are possible even with [email protected], I've tried it, but somehow I am unable to compile my code anyway.

推荐答案

您需要在标记为异步"函数的函数中使用asyncFn.例如:

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

这篇关于TypeScript:找不到名称异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:21