0

I've database of users where they have created their team. and other document for storing racers.

each user can create a team of 6 racers.

but the problem is that I've 50k users and using the below code to remove a racer from their team if Admin deleted it from Racers Document.

I'm using express.js and mongoose

team is an array of object which has racers name, it's shortCode and unique identifier.

async function delete(req, body){
    // code to validate users input
    await Users.updateMany({'tema.shortCode': 'HAM'}, { $pull: {'team.shortCode': 'HAM'}})

}

I've seen that response time decreases if i remove await keyword. But is it recommended to do that.

  • I would say leave the `await` in there but if you want to improve the apparent speed of your frontend, you can just not `await` the response from the server. This way if you want to wait for the server response you can, and if not, you don't have to. – Henry Woody Mar 05 '22 at 19:55
  • Are you looping? It be good to see this code. – beautifulcoder Mar 05 '22 at 20:27
  • I'm not looping, I'm using same query in a async function as shown in example – Abhay Singh Mar 06 '22 at 17:04

1 Answers1

3

No, you shouldn't remove the await. Removing the await means that if the Users.updateMany call rejects, the error won't be able to be handled easily as it would become an unhandled promise rejection.

const fail = async message => Promise.reject(message)

const usingAwait = async () => {
  await fail('using await')
}


const noAwait = async () => {
  fail('no await')
}

const handleError = error => console.log('Handled error:', error)

;(async () => {
  await usingAwait().catch(handleError) // logs Handled error: using await
  await noAwait().catch(handleError) // doesn't log anything!
})()

The typescript-eslint rule @typescript-eslint/no-floating-promises has some more details on this:

Unhandled promises can cause several issues, such as improperly sequenced operations, ignored Promise rejections and more. Valid ways of handling a Promise-valued statement include awaiting, returning, and either calling .then() with two arguments or .catch() with one argument.

The way to speed things up would be to use something like Promise.all if you're doing multiple deletes that don't depend on the result of each other:

const reqs = [[req1, body1], /* ... */]
await Promise.all(reqs.map(async ([req, body]) => delete(req, body))
Lauren Yim
  • 12,700
  • 2
  • 32
  • 59