如何在node.js中等待流式SQL查询

我需要调出具有行级功能的运行sql查询的函数,并等待整个过程再继续。

功能代码:

const sql = require('mssql')

exports.doit = ()=>{
    const pool1 = new sql.ConnectionPool(dbConfig);
    const pool1Connect = pool1.connect();

    pool1.on('error',err => {
        console.error('error occurred on pool')
    })
    await pool1Connect
    try {
        const request = pool1.request();
        request.stream = true;
        request.query('select * from dbo.user');
        request.on('row',async orow => {
            console.log('outer row');
            const innerPool = new sql.ConnectionPool(dbConfig);
            const innerConnection = innerPool.connect();
            innerPool.on('error',err => {
                console.error('error occurred on pool')
            });
            const iConnection = await innerConnection;
            connections.push(iConnection);

            const innerRequest = innerPool.request();
            innerRequest.stream = true;
            var iquery = 'select * from dbo.order where userId='+ orow.userId
            innerRequest.query(iquery);

            innerRequest.on('row',async irow => {
                console.log(`User: ${orow.userId} Order: ${irow.orderId}`);
            });

            innerRequest.on('done',async () => {
                console.log('inner done');
                iConnection.close();
            });
        });
        request.on('done',async () => {
            console.log('outer done');
        })
    } catch (err) {
        console.error('SQL error',err);
    }
    sql.on('error',err => {
        // ... error handler
    })
}

然后像这样调用上面的函数:

var doit = require('./testmeHandler.js').doit;

 doit()
 .then(()=>{
     console.log("I AM DONE");
 });

OR

await doit();
console.log('I AM DONE');

您明白了...

但是真正发生的是,先调用该函数,然后调用“ I AM DONE”,然后调用所有sql的结果。

有人可以帮助我在底部显示“我已完成”吗?仍然习惯了异步/等待和诺言。

谢谢

guoguo337 回答:如何在node.js中等待流式SQL查询

以某种方式,我相信您已经将所有内容弄乱了。

使用此

exports.doit = async ()=>
{
const request = new sql.Request(conn)
let records = await request.query('select * from dbo.user')

records.forEach(async r=>{
    try{
        // do something
        const inner = new sql.Request(conn)
        let recordInner = await request.query(innerQuery)
        recordInner.forEach(async r=>{//do some stuff})
        inner.close()
    }
    catch(err){
            //do something with the error
    }
    records.close()
})
}

执行:

async execute(){
    const result = await doit()
    return result
}

execute()

尽管我不知道您为什么要使用两个连接。只需尝试使用JOINWHERE子查询编写一个更定义的查询。您可以在单个查询中而不是使用嵌套连接来实现所有这些功能。 SQL虽然有些陈旧,但确实非常强大。

select * from dbo.order WHERE userId IN (SELECT userId FROM dbo.user)

对我来说更有意义。但是,无论漂浮在船上。

有关子查询的更多信息:https://www.dofactory.com/sql/subquery

,

经过一段时间后,我尝试让它从调用方同步运行,我放弃了,重新编写了使用常规查询(非流式处理)的方法,并实现了自己的分页/限制以控制内存使用。现在效果很好!

我正在使用连接池来允许子查询和其他进程在一批结果中异步发生。

我将发布更新的代码。

本文链接:https://www.f2er.com/2938335.html

大家都在问