Javascript 嵌套异步不返回结果

问题描述 投票:0回答:1

出于某种原因,第二个嵌套的异步数据库函数永远不会得到返回的结果。第一个数据库调用从 MSSQL 获取一些计划程序,以便对 OracleDB 进行第二次数据库调用。当我在显示的数据库函数中获得结果时,我可以看到 Oracle 查询有效。

 app.get('/api/Scrap/:ParmLocation/:ParmDepartment', (req, res) => {
    var ParmLocation = req.params.ParmLocation;
    var ParmDepartment = req.params.ParmDepartment;
    console.log('/api/Scrap called for ' + ParmLocation + ' Department ' + ParmDepartment + ' @ ' + Date());

    // First get planners for this department
    var query = `SELECT Planners FROM DeptPlanners where Department = '${ParmDepartment}'`
    var PromisePlanners = db.DBQueryBHBrowser(query);
    var Planners = '';
    PromisePlanners.then(function(result) {
        result.recordset.forEach(function(row){
            Planners = Object.values(Object.values(row))[0];
        });
        console.log('/api/Scrap Planners completed @ ' + Date());
        console.log('Planners: ' + Planners);
        var query = `SELECT TO_CHAR(TO_DATE(SUBSTR(ILTRDJ,-5), 'YYDDD'),'WW') AS Week, SUM(ILTRQT / 1000 * -1) AS TOTQTY, SUM(ILPAID / 100 * -1) AS TOTAMT
        FROM PRODDTA.F4111
        JOIN PRODDTA.F4102 ON ILITM = IBITM AND IBMCU = ILMCU AND IBANPL NOT IN (50030002,50030039)
        JOIN PRODDTA.F4101 ON IMLITM = ILLITM
        JOIN PRODCTL.F5500001 On ILTRDJ = DCGRDT
        LEFT JOIN PRODCTL.F0005 ON ILRCD= LTRIM(F0005.Drky)
        And DRSY='42' AND DRRT='RC'
        WHERE ILMCU = '       50010' AND ILDCT IN('ID', 'IS')
        AND ILTRDJ BETWEEN  123001 AND 123365
        AND IBANPL IN (${Planners})
        AND ILRCD NOT IN('517','509') AND ILUSER <> 'HIPPK'
        GROUP BY TO_CHAR(TO_DATE(SUBSTR(ILTRDJ,-5), 'YYDDD'),'WW')
        ORDER BY Week`

        var PromiseScrap = db.DBQueryJDE(query);
        PromiseScrap.then(function(result) {
            //if (debugMode == true) {
                console.log(`/api/Scrap ${ParmLocation} ${ParmDepartment}  completed @ ${Date()}`);
                console.log(`JDE Data:` + result );      // This is always 'Undefined'
            //}
            res.send(result);
        }).catch(function () {
            console.log("Promise Rejected for api/Scrap");
        });
    }).catch(function () {
        console.log("Promise Rejected for /api/Scrap get Planners");
    });
})

第二次调用DBQueryJDE有

    async function DBQueryJDE(sqlquery)  {
  try {
    //if (debugMode) {
      console.log('Oracle SQL:\n' + sqlquery);
    //}
    var oracledb = require('oracledb');
    var connectionProperties = {
      user: process.env.DBAAS_USER_NAME || "SomeUserID",
      password: process.env.DBAAS_USER_PASSWORD || "SomePassword",
      connectString: "(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = db92IF.bherp.local)(PORT = 1521))(CONNECT_DATA =(SERVICE_NAME= DB92IF.bherp.local)))"};
    oracledb.getConnection(connectionProperties, function (err, connection) {
      if (err) {
        console.error(err.message);
        response.status(500).send("Error connecting to DB");
        return;
      }
      connection.execute(sqlquery,
        function (err, result) {
          if (err) {
            console.error(err.message);
            response.status(500).send("Error getting data from JDE DB");
            doRelease(connection);
            return;
          }
          console.log("RESULTSET:" + JSON.stringify(result));
          doRelease(connection);
          //console.log('returned from close');
          return result;
        }
      );
    });
    //return result;
  } catch (error) {
      console.log('DBErrorJDE: ' + err.message + '\n Query:' + sqlquery);
      doRelease(connection);
      return;
  }
};

控制台的结果是

节点应用 监听端口 3000

的仪表板服务器

/api/Scrap 要求 BHNW 部门歧管 @ 2023 年 5 月 3 日星期三 09:19:54 GMT-0400(东部夏令时间)

/api/Scrap Planners 已于 2023 年 5 月 3 日星期三 09:19:54 GMT-0400(东部夏令时间)完成

策划:50030015,50030029

Oracle SQL: SELECT TO_CHAR(TO_DATE(SUBSTR(ILTRDJ,-5), 'YYDDD'),'WW') AS Week, SUM(ILTRQT / 1000 * -1) AS TOTQTY, SUM(ILPAID / 100 * -1)作为TOTAMT 来自 PRODDTA.F4111 在 ILITM = IBITM 和 IBMCU = ILMCU 和 IBANPL 上加入 PRODDTA.F4102 不在 (50030002,50030039) 在 IMLITM = ILLITM 上加入 PRODDTA.F4101 在 ILTRDJ = DCGRDT 上加入 PRODCTL.F5500001 在 ILRCD= LTRIM(F0005.Drky) 上左加入 PRODCTL.F0005 和 DRSY='42' 和 DRRT='RC' WHERE ILMCU = '50010' AND ILDCT IN('ID', 'IS') 和 ILTRDJ 在 123001 和 123365 之间 和 IBANPL 在 (50030015,50030029) AND ILRCD NOT IN('517','509') AND ILUSER <> 'HIPPK' GROUP BY TO_CHAR(TO_DATE(SUBSTR(ILTRDJ,-5), 'YYDDD'),'WW') 按周排序

/api/Scrap BHNW 歧管已完成 @ 2023 年 5 月 3 日星期三 09:19:54 GMT-0400(东部夏令时间)

JDE数据:未定义

RESULTSET:{"metaData":[{"name":"WEEK"},{"name":"TOTQTY"},{"name":"TOTAMT"}],"rows":[["01", 24,1573.83],["02",35,2096.06],["03",26,903.28],["04",16,729.95],["05",25,873.44],["06",61,2015.3500000000001],[ "07",28,2293.91],["08",23,1223.8500000000001],["09",24,800.9],["10",41,1366.04],["11",17,1712.95],["12 ",30,1588.1200000000001],["13",45,1189.51],["14",33,1104.3],["15",71,2378.3],["16",38,1430.72],["17 ",35,2559.43],["18",22,725.89]]}

javascript asynchronous promise nested
1个回答
-1
投票

您的问题是您在嵌套函数中混合使用了

callback
async/promise

您正在调用嵌套函数

DBQueryJDE
如下:

const result = await DBQueryJDE(query)

但是函数的实现方式——它总是会返回

undefined
.

原因是您正在从回调中返回结果——它没有返回给调用者。

即这就是你在做什么

function DBQueryJDE(queryString) {
     // when you get a connection - you then execute a callback function which is passed the connection
     oracledb.getConnection(args, (connection) => {
          // when connection.execute is executed - the following callback is executed with the results
          connection.execute(queryString, (results) => {
              // now you have the results - you need to either execute another callback or do nothing as this cannot be returned via the existing pattern
              return results; // this does not get returned to the caller.
          }
     })

}

根据他们的示例,从

oracledb
的 5.5 版开始 - 他们支持承诺,因此您可以按如下方式修改,此返回将返回给调用者。

为了更好地理解,我建议您阅读回调和异步/承诺之间的区别。

const connection = await oracledb.getConnection(connectionProperties); 
return connection.execute(sqlquery);

(您可以使用 oracledb async,或者您也可以自己滚动并将 DBQueryJDE 函数内部回调包装在 Promise 中,如下所示)

async function DBQueryJDE(sqlquery)  {
      try {
        ...
        return new Promise((resolve, reject) => { 
            oracledb.getConnection(connectionProperties, function (err, connection) {
            if (err) return reject(err);
          
            connection.execute(sqlquery, function (err, result) {
               if (err) return reject(err)
                 return resolve(result);
            });
        });
      } catch (error) {
        ...
      }
    };
© www.soinside.com 2019 - 2024. All rights reserved.