为了账号安全,请及时绑定邮箱和手机立即绑定

如果返回标记值,则停止等待剩余的承诺

如果返回标记值,则停止等待剩余的承诺

翻阅古今 2023-01-06 16:00:43
我有一个函数 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'    }
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

Promise.all一旦任何包含的承诺被拒绝,返回的承诺将被拒绝。考虑到这一点,您可以抛出哨兵值而不是返回它,只需在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'

}


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信