1

So, I am doing a course on web development and I'm doing mongoDB middleware stuff and I noticed the teacher was using an async function instead of a simple one and I really don't see the difference, I mean I understand the concept but I don't see how would it change the code's behavior.

personSchema.pre("save", async function(){
    console.log("Saving...");
});

personSchema.post("save", async function(){
    console.log("SAVED!");
});
Scythe
  • 31
  • 3
  • If the callback function involves a DB operation, it needs to `await` for the promise to resolve or reject. That's why your middlware has `async function()` – Ozgur Sar Jan 13 '21 at 07:27
  • Yes, i get it now, I tried without the async keyword and the behaivor was the same (in my simple case), thanks! – Scythe Jan 13 '21 at 07:52
  • If your callback function doesn't involve an asynchronous operation, there is no point to use the `async` keyword in front of the `function` – Ozgur Sar Jan 13 '21 at 07:59
  • That function is the `callback( )` from the **save** command. As it was said by @OzgurSar, you only need async if the callback executes asynchronous code. This is not always the case, so "async" as a rule is just playing silly. – Minsky Jan 13 '21 at 09:38

0 Answers0