Unable to understand why the try and catch is not working as expected in mongoose
First let’s take a look at a function that uses a synchronous usage pattern.
// Synchronous usage examplevar result = syncFn({ num: 1 });// do the next thing
When the function syncFn
is executed the function executes in sequence until the functionreturns and you’re free to do the next thing. In reality, synchronous functions should bewrapped in a try/catch. For example the code above should be written like this:
// Synchronous usage examplevar result;try { result = syncFn({ num: 1 }); // it worked // do the next thing} catch (e) { // it failed}
Now let’s take a look at an asynchronous function usage pattern.
// Asynchronous usage exampleasyncFn({ num: 1 }, function (err, result) { if (err) { // it failed return; } // it worked // do the next thing});
When we execute asyncFn
we pass it two arguments. The first argument is the criteria to be used by the function. The second argument is a callback that will execute whenever asyncFn
calls the callback. asyncFn
will insert two arguments in the callback – err
and result
). Wecan use the two arguments to handle errors and do stuff with the result.
The distinction here is that with the asynchronous pattern we do the next thing within the callback of the asynchronous function. And really that’s it.