【问题标题】:How to use assert within async functions? (Typescript)如何在异步函数中使用断言? (打字稿)
【发布时间】:2016-06-14 21:49:33
【问题描述】:

我有一个像下面这样的块,它是一个使用async 的函数 如果我在其中添加一个断言语句,它将停止在该行执行的代码,但不会引发错误。它只是默默地死去:(

async function testMongo() {
  let db = await dbConnect();

  await db.collection("stories").remove({});
  let c = await count("stories", {} );
  assert.strictEqual(c, 999);   // should fail
  console.log("moving on...");  /// will never get reached.

}

断言可能被吞没有什么原因吗? 我之前遇到过类似的问题,事件发射器内部出现错误,并且异步函数的立即返回似乎是某种类型的事件发射器/Promise。

【问题讨论】:

    标签: typescript async-await assert


    【解决方案1】:

    console.log() 如果异步 db.connection() 或 count() 将拒绝他们的承诺,则可以跳过调用。在这种情况下,您应该尝试将这些调用包装在 try/catch 中:

    try
    {
        await db.collection("stories").remove({});
    }
    catch(e)
    {
        //...    
    }
    

    或者使用 promise 捕获错误:

    await db.collection("stories").remove({}).catch((e) => {//...});
    

    [编辑]

    将执行异步函数并在被拒绝时继续执行的通用包装器可能如下所示:

    async function Do<T>(func: ()=>Promise<T>)
    {
        try
        {
            await func();
        }
        catch(e)
        {
            console.log(e);  
        }
    }
    

    【讨论】:

    • 我想知道是否有办法将所有awaited 函数推入通用包装器中?
    猜你喜欢
    • 2018-05-03
    • 2016-04-19
    • 2023-02-14
    • 1970-01-01
    • 2017-03-19
    • 2019-01-08
    • 1970-01-01
    • 2019-04-30
    • 2017-12-01
    相关资源
    最近更新 更多