Search code examples
javascriptnode.jsdatabaseasynchronousmapr

Querying multiple promises with a callback


In node.js i have a databaseMapper.js file, that uses the Ojai node MapR api. to extract data. So far i have it working with single documents, but since this is an async api, i have a bit of issues with querying multiple documents.

This is what i have so far:

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();
}
}

here it will only return the first because queryResultPromise will resolve on the first document.. however the callback with "data" may occur multiple times, before the queryResult will end like this queryResult.on('end', () => connection.close())

i tried using something like Promise.all() to resolve all of them, but I'm not sure how i include the queryResult.on callback into this logic


Solution

  • This will work

        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);
                })
            });
        };