如何(正确地)在 Node 中链接多个顺序 MSSQL 查询

How to (properly) chain multiple sequential MSSQL queries in Node

我正在编写一个简单的 nodejs CLI 工具,同时学习 promises(以避免回调地狱),我发现的每个 tutorial/Whosebug 示例只展示了如何进行单个调用。我的用例如下: 1.连接到数据库(我可以做到) 2.执行一个SQL select语句(这部分也搞定了) 3.对结果做一些事情 4. 重复步骤2 & 3几次

我正在收集 MSSQL 用户名和密码(使用硬编码服务器 'localhost' 和数据库名称 'testdb'),所以当应用程序执行时我不能只跳入 MSSQL 连接。

我可以通过回调得到这个,但现在我有大约 50 个查询,所以你可以想象这有多丑。下面的完整代码确实让我得到了第一个查询,我强烈怀疑我没有将 "pool" 对象传递给下一个 "then",但是当我尝试

.then((pool,result) => {
   //next command
})

它仍然不识别池

这是代码 (index.js):

const mssql = require('mssql');

const qry1 = "select fieldA from tblA";
const qry2 = "select fieldB from tblB";
const qry3 = "select fieldC from tblC";
var dbuser = '';
var dbpass = '';
var config = {}

function init() {
   log('Beginning Audit');
   collectDbInfo(); //The reason I don't just included it all here
}

function collectDbInfo() {
    //code is irrelevant to the problem, this is where I'm collecting the database credentials
}

function start() {
   config = {
      user: dbuser,
      password: dbpass,
      server: 'localhost',
      database: 'testdb'
   }

   mssql.connect(config)
      .then(pool => {
         //FIRST query
         return pool.request().query(qry1)
      })
      .then(result => {
         processQryA(result);
         //SECOND query
         return pool.request().query(qry2)
      })
      .then(result => {
         processQryB(result);
         //THIRD query
         return pool.request().query(qry3)
      })
      .then(result => {
         processQryC(result);
      })

   mssql.on('error',err => {
      log('SQL Error:' err)
      mssql.close();
      process.exit(0);
   }
}

processQryA(data) {
    console.log(data.recordset[0].fieldA)
}

processQryB(data) {
    console.log(data.rcordset[0].fieldB)
}

processQryC(data) {
    console.log(data.recordset[0].fieldC)
}

init();

我非常感谢我可能完全错误地处理了这一切,所以任何建议或特别是示例将不胜感激。

如果查询本质上是绝对顺序的,您可以使用 async/await:

来实现
async function start(){
        config = {
            user: dbuser,
            password: dbpass,
            server: 'localhost',
            database: 'testdb'
         }
        try {
            pool = await mssql.connect(config);
            const res1 = await pool.request().query(qry1);
            processQryA(res1);
            const res2 = await pool.request().query(qry2);
            processQryB(res2);
            const res3 = await pool.request().query(qry3);
            processQryC(res3);
            const res4 = await pool.request().query(qry4);
            processQryD(res4);
            /*..And so on with rest of sequential queries*/
            /*Any of them resulting in error will be caught in (catch)*/

        } catch (error) {
            console.error("Error in start()::", error);
        }
    }

Also: I would probably have my pool getting method separately from query executions to handle errors/validations nicely.