Home > OS >  Should I remove "await" keyword to increase response time?
Should I remove "await" keyword to increase response time?

Time:03-07

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.

CodePudding user response:

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))
  • Related