首页 > 解决方案 > 如果返回哨兵值,则停止等待剩余的承诺

问题描述

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

标签: javascripttypescript

解决方案


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'
}

推荐阅读