【问题标题】:How can I run a top level async / await function with TypeScript?如何使用 TypeScript 运行顶级 async / await 函数?
【发布时间】:2020-05-05 02:11:34
【问题描述】:

我的文件是:

import * as fs from 'fs'

async function loadModels() {
    console.log('here i am!')
    const modelFiles = fs.readFileSync(__dirname + '/models')
    console.log(modelFiles)
}


(async () => {
    loadModels()
})()

package.json,我有:

"fixtures": "tsc fixtures/index"

所以当我运行yarn fixtures 时,我得到:

yarn fixtures
yarn run v1.22.4
$ tsc fixtures/index
✨  Done in 8.78s.

为什么我的loadModels 不运行?

【问题讨论】:

  • 为什么文件系统fs需要异步/等待?
  • loadModels 确实以这种结构运行。 See playground.
  • 附带说明:此代码中的任何地方都不需要 async 关键字。

标签: javascript node.js typescript async-await


【解决方案1】:

tsc 只是在编译你的 TypeScript 文件,而不是在执行它

要执行你的 TypeScript 文件,你可以使用 ts-node package

然后在你的package.json:

"fixtures": "ts-node fixtures/index"

【讨论】:

  • 也可以构建并运行而不是使用ts-node 包。在你的 package.json 中:"fixtures": "tsc&&node fixtures/index.js".
  • 是的,当然可以,但我猜这个文件只用于开发目的,所以不应该编译到最终应用程序中
猜你喜欢
  • 2020-08-01
  • 2021-01-14
  • 2018-01-16
  • 2017-12-17
  • 2019-04-13
  • 1970-01-01
相关资源
最近更新 更多