Home > Blockchain >  NodeJS - Is it OK to call db insert/update functions without await?
NodeJS - Is it OK to call db insert/update functions without await?

Time:12-06

I have a backend application and there are insert/update endpoints. They mostly go as:

  1. Check and validate the input
  2. Submit the input to db
  3. Return status 200/201 with location header set and body contains status message

Would it be ok to make the 2nd step without await so that response can be returned faster? The returned status will be set to 202, which means it is currently processing. The possibility of 2nd step to throw error is extremely low, or if it does there is a bug going on somewhere and does not relate to the end-user anyways, hence no need to return such error to user.

Would this work? Even if this works, would it be a good practice?

CodePudding user response:

It's OK to not wait for the database response to succeed before doing other things (like sending back a response) if that's how you want your app to work and you're sure that's the right design and you've thought through what happens (from the end user's point of view) if that database call (that you didn't wait for) fails.

BUT, it's not OK to ignore a rejected promise that might come back from the database call because unhandled promise rejections should not happen in a nodejs server. So, if you're not going to use an await, then you probably need a .catch() to catch and at least log the error.

Would this work?

Yes. There's nothing in the language or in nodejs stopping your from sending a response before the database call has completed. It's more about whether that's the appropriate way to design your response handler.

Even if this works, would it be a good practice?

It's not a widely recommended practice because the usual sequence is this:

  1. Check and validate the input
  2. Submit the input to db
  3. If success, return status 200/201 with location header set and body contains status message
  4. If error, return appropriate error status (based on type of error) and status message.

I'm not saying that you can never deviate from this sequence, but doing so would generally be the exception, not the rule.

Keep in mind that data validation does not necessarily catch everything that might cause the database to generate an error. For example, you could be creating a new user on your site and the email address is perfect valid in validation, but then the database rejects it because it's not unique (there's already a user with that email address).

And, the database itself could be having problems, causing an error and the user should be informed that the transaction they were trying to submit to the database did not happen event though the error was not directly caused by the user.

  • Related