我有一个validateTables()函数,该函数使用对每个查询API的异步帮助函数queryTable()的调用(每个表)来验证数据是否存在于多个表中。要通过验证,每个表中都必须存在数据。如果表为空,则辅助函数将返回false。我目前在Promise.all()中拥有一组调用,用于检查结果数组中是否有错误值。为了提高性能,我宁愿在诺言解析为假时也不再等待所有剩余诺言的解决。Promise.race()和.all()不起作用,因为它们与承诺何时或是否能够解决有关,而不是返回值。我可以做到这一点而又不会失去异步功能的并行处理吗?
通用功能:
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
只要包含的任何承诺被拒绝,由的返回的承诺就会被拒绝。考虑到这一点,您可以抛出哨兵值而不是返回它,而只需在的try / catch中检查该值即可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'
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句