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

我有一个函数 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'

    }


翻阅古今
浏览 129回答 1
1回答

湖上湖

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'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript