0

I have a block like below, which is a function using async If I add an assert statement in there, it will stop the code executing at that line, but no error is thrown. It just dies silently :(

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.

}

Is there some reason that the assertion maybe gets swallowed up? I've had problems like these before with errors inside event emitters, and it seems the immediate return of the async function is some type of event emitter/Promise.

1 Answer 1

1

console.log() call can be skipped is if async db.connection() or count() will reject their promises. It this case your should try wrapping those calls in try/catch:

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

Or catch error using promise:

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

[EDIT]

The generic wrapper that will execute async function and continue even on rejection can look something like this:

async function Do<T>(func: ()=>Promise<T>)
{
    try
    {
        await func();
    }
    catch(e)
    {
        console.log(e);  
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

i wonder if there's a way to push than into a generic wrapper for all awaited functions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.