javascript - 如果返回哨兵值,则停止等待剩余的承诺
问题描述
我有一个函数 validateTables(),它使用对查询 api 的异步帮助函数 queryTable() 的调用(每个表)来验证数据是否存在于多个表中。要通过验证,数据必须存在于每个表中。如果表为空,辅助函数将返回 false。我目前在 Promise.all() 中有一组调用,用于检查结果数组中是否存在任何错误值。为了性能,我宁愿停止等待任何剩余承诺的解决,如果并且当一个承诺解决为假时。Promise.race() 和 .all() 不起作用,因为它们关心的是何时或是否解决了 promise,而不是返回值。我可以在不丢失异步函数的并行处理的情况下做到这一点吗?
广义函数:
async queryTable(query, params) {
try {
returnData = []
for await (const returnItem of api.executeQuery(query, params)){
returnData.push(returnItem)
}
if (returnData.length > 0) {
return true;
}
return false;
}
catch (err) {
throw new Error(`${JSON.stringify(err)}`);
}
}
async validateTables() {
const allDataExists = await Promise.all([
this.queryTable(query, params),
this.queryTable(query2, params2),
this.queryTable(query3, params3),
// and so on for several more
])
if (!allDataExists.includes(false)) {
return 'OK'
}
return 'Invalid'
}
解决方案
Promise.all
一旦任何包含的 Promise被拒绝,则返回的 Promise将被拒绝。考虑到这一点,您可以抛出哨兵值而不是返回它,并简单地在await
.
async queryTable(query, params) {
try {
returnData = []
for await (const returnItem of api.executeQuery(query, params)){
returnData.push(returnItem)
}
if (returnData.length > 0) {
return true;
}
throw false;
}
catch (err) {
throw new Error(`${JSON.stringify(err)}`);
}
}
async validateTables() {
try {
const allDataExists = await Promise.all([
this.queryTable(query, params),
this.queryTable(query2, params2),
this.queryTable(query3, params3),
// and so on for several more
])
} catch(e) {
if(e instanceof Error) throw e
return 'Invalid'
}
return 'OK'
}
推荐阅读
- string - 你能转换未来吗
到一个字符串?颤振/飞镖 - azure-web-app-service - 具有 VNET 集成的应用服务无法连接到同一 VNET 中的 HTTP 终结点
- java - Apache Ignite - 使用 Affinity Key 读取所有键、值
- database - 如何:具有大型数据库和快速访问一小部分数据的 Spring Boot 应用程序
- oracle - 如何在 Oracle Business Intelligence 11.1.1.9.0 (OBIEE) 的列级别添加切换按钮
- python - 如何解决 HTTP 错误 429:请求过多?
- ios - (SIGABRT 尝试使用未知类项目名称)Xcode 11、Swift 5、iOS 13 中强引用变量上的 EXC_BAD_ACCESS 错误
- laravel - Laravel - 无法使用用户名在 SMTP 服务器上进行身份验证
- wordpress - 以水平方式按年和月显示存档
- leaflet - 当我允许跟踪我的位置时,尝试在我的确切位置上显示自定义标记