如何使用打字稿使用顶级异步等待?

时间:2020-09-03 06:32:21

标签: node.js typescript

我有一个打字稿项目,当我在顶层使用operator[]时,打字稿短绒会显示出来,

await xxx.someAsyncMethod(..)

所以我将模块更改为esnext Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.

我将继续尝试运行程序"module": "esnext"

然后控制台通知我

npx ts-node app/app.ts

在运行控制台输出的程序时,将类型设置为package.json (node:15509) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. Cannot use import statement outside a module 中的模块

"type": "module"

该怎么办,这样我才能摆脱使用顶级异步等待的麻烦?

编辑: 我的redis.ts文件

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/apple/Desktop/source_given_to_me/Git/bots/wab/app/app.ts
    at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
    at Loader.getFormat (internal/modules/esm/loader.js:113:42)
    at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
    at Loader.import (internal/modules/esm/loader.js:178:17)

我的config.ts文件(下面是tsconfig.json)


import * as pm from "child_process"
var prc:pm.ChildProcess;

async function startRedis(path:string): Promise<boolean> {
    return new Promise((resolve) => {
        console.log('starting redis')
        var rp = pm.spawn(path)
        rp.stdout.on("data", (data) => {
            console.log(data)
            console.log('redis fired up')
            prc= rp
            resolve(true)
        })
        rp.stderr.on("data", (data) => {
            console.log(data)
            console.log('redis failed to start')
            resolve(false)
        })
    })
}

function active():boolean{
    return prc?!prc.killed:false
}

async function stopRedis(): Promise<boolean> {
    return new Promise(
        (resolve)=>{
            if(prc){
                resolve(prc.kill("SIGTERM"))
            } else {
                resolve(false)
            }
        }
    )
}


export const redis = {
    startRedis,
    stopRedis,
    active
}


我的app.ts文件

export const config = {
    redisPath:'../r607/src/redis-server'
}

我的tsconfig.json

import {config} from "./config.js"
import {redis} from "./redis.js"
//import * as pm from "child_process"

await redis.startRedis(config.redisPath)
if(!redis.active()){
    process.abort()
}

0 个答案:

没有答案