简体   繁体   English

使用回调查询多个承诺

[英]Querying multiple promises with a callback

In node.js i have a databaseMapper.js file, that uses the Ojai node MapR api.在 node.js 中,我有一个databaseMapper.js文件,它使用 Ojai 节点 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.到目前为止,我使用的是单个文档,但由于这是一个异步 api,我在查询多个文档时遇到了一些问题。

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())在这里它只会返回第一个,因为queryResultPromise将在第一个文档上resolve ......但是带有"data"的回调可能会发生多次,在 queryResult 将像这样结束之前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我尝试使用Promise.all()类的东西来解决所有这些问题,但我不确定如何将queryResult.on回调包含到这个逻辑中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM