使用回调查询多个承诺

Querying multiple promises with a callback

在 node.js 中,我有一个 databaseMapper.js 文件,它使用 Ojai 节点 MapR api。提取数据。到目前为止,我只处理单个文档,但由于这是一个异步 api,我在查询多个文档时遇到了一些问题。

这是我目前拥有的:

function queryResultPromise(queryResult) {
//this should handle multiple promises
    return new Promise((resolve, reject) => {
        queryResult.on("data", resolve);
        // ...presumably something here to hook an error event and call `reject`...
    });
}



const getAllWithCondition = async (connectionString, tablename, condition) =>{
    const connection = await ConnectionManager.getConnection(connectionString);
    try {
        const newStore = await connection.getStore(tablename);
        const queryResult = await newStore.find(condition);
        return await queryResultPromise(queryResult);
    } finally {
        connection.close();
}
}

这里它只会 return 第一个,因为 queryResultPromiseresolve 在第一个文档上..然而 "data" 的回调可能会发生多次,在queryResult会这样结束queryResult.on('end', () => connection.close())

我尝试使用 Promise.all() 之类的方法来解决所有这些问题,但我不确定如何将 queryResult.on 回调包含到此逻辑中

这会起作用

    const queryResultPromise = (queryResult) => {
        return new Promise((resolve, reject) => {
            let result = [];
            queryResult.on('data', (data) => {
                result.push(data)
            });
            queryResult.on('end', (data) => {
                resolve(result);
            });
            queryResult.on('error', (err) => {
                reject(err);
            })
        });
    };