我应该删除 "await" 关键字以增加响应时间吗?
Should I remove "await" keyword to increase response time?
我有他们创建团队的用户数据库。和其他用于存储赛车手的文件。
每个用户可以创建一个由 6 名赛车手组成的车队。
但问题是我有 50k 用户,如果管理员从 Racers Document 中删除了赛车手,我会使用以下代码从他们的团队中删除赛车手。
我正在使用 express.js 和猫鼬
team 是一个包含赛车手名称的对象数组,它是短代码和唯一标识符。
async function delete(req, body){
// code to validate users input
await Users.updateMany({'tema.shortCode': 'HAM'}, { $pull: {'team.shortCode': 'HAM'}})
}
我发现如果删除 await 关键字,响应时间会缩短。但是否推荐这样做。
不,您不应该删除 await
。删除 await
意味着如果 Users.updateMany
调用被拒绝,错误将无法轻松处理,因为它会变成 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!
})()
typescript-eslint 规则 @typescript-eslint/no-floating-promises 对此有更多详细信息:
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 await
ing, returning, and either calling .then()
with two arguments or .catch()
with one argument.
如果您正在执行多个不依赖于彼此结果的 delete
,则加快速度的方法是使用类似 Promise.all
的方法:
const reqs = [[req1, body1], /* ... */]
await Promise.all(reqs.map(async ([req, body]) => delete(req, body))
我有他们创建团队的用户数据库。和其他用于存储赛车手的文件。
每个用户可以创建一个由 6 名赛车手组成的车队。
但问题是我有 50k 用户,如果管理员从 Racers Document 中删除了赛车手,我会使用以下代码从他们的团队中删除赛车手。
我正在使用 express.js 和猫鼬
team 是一个包含赛车手名称的对象数组,它是短代码和唯一标识符。
async function delete(req, body){
// code to validate users input
await Users.updateMany({'tema.shortCode': 'HAM'}, { $pull: {'team.shortCode': 'HAM'}})
}
我发现如果删除 await 关键字,响应时间会缩短。但是否推荐这样做。
不,您不应该删除 await
。删除 await
意味着如果 Users.updateMany
调用被拒绝,错误将无法轻松处理,因为它会变成 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!
})()
typescript-eslint 规则 @typescript-eslint/no-floating-promises 对此有更多详细信息:
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
await
ing, returning, and either calling.then()
with two arguments or.catch()
with one argument.
如果您正在执行多个不依赖于彼此结果的 delete
,则加快速度的方法是使用类似 Promise.all
的方法:
const reqs = [[req1, body1], /* ... */]
await Promise.all(reqs.map(async ([req, body]) => delete(req, body))