【问题标题】:Connection is not defined in oracledboracledb 中未定义连接
【发布时间】:2020-10-15 20:49:31
【问题描述】:

我正在使用 oracledb cen node.js 模块,在建立数据库连接进行选择时,它会返回数据但也会出现此错误:

(node:1) UnhandledPromiseRejectionWarning: ReferenceError: connection is not defined
    at Object.getTest (/home/src/storage/oracleDb.js:29:9)
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 1)
(node:1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我这样查询:

 try {
        await oracledb.getConnection(config.db)
        .then(function (conn) {
            return conn.execute(querys.queryTest());
        }, function(err) {
            console.log(err);
        })
        .then(function (result) {
            console.log('Query executed');
            console.log(result.rows[0]);
        }, function(err) {
            console.log(err);
        })
        .catch(function(err) {
            console.log(err);
        });

    } catch (error) {
        console.log(error);
    } finally {
        if (connection) {
            try {
                await connection.close();
            } catch (err) {
                console.error(err);
            }
        }
    }

【问题讨论】:

  • 应该是conn而不是connection。

标签: javascript node.js oracle es6-promise node-oracledb


【解决方案1】:

如果您可以使用await,那么您就处于async 函数中。如果您在 async 函数中,为什么要使用承诺链?

下面是这种类型的代码在 Promises 中的样子:

const oracledb = require('oracledb');

function getEmployee(empId) {
  return new Promise(function(resolve, reject) {
    let conn; // Declared here for scoping purposes.

    oracledb
      .getConnection()
      .then(function(c) {
        console.log('Connected to database');

        conn = c;

        return conn.execute(
          `select *
          from employees
          where employee_id = :emp_id`,
          [empId],
          {
            outFormat: oracledb.OBJECT
          }
        );
      })
      .then(
        function(result) {
          console.log('Query executed');

          resolve(result.rows[0]);
        },
        function(err) {
          console.log('Error occurred', err);

          reject(err);
        }
      )
      .then(function() {
        if (conn) {
          // If conn assignment worked, need to close.
          return conn.close();
        }
      })
      .then(function() {
        console.log('Connection closed');
      })
      .catch(function(err) {
        // If error during close, just log.
        console.log('Error closing connection', err);
      });
  });
}

module.exports.getEmployee = getEmployee;

下面是使用 async/await 的样子:

const oracledb = require('oracledb');

function getEmployee(empId) {
  return new Promise(async function(resolve, reject) {
    let conn; // Declared here for scoping purposes.

    try {
      conn = await oracledb.getConnection();

      console.log('Connected to database');

      let result = await conn.execute(
        `select *
        from employees
        where employee_id = :emp_id`,
        [empId],
        {
          outFormat: oracledb.OBJECT
        }
      );

      console.log('Query executed');

      resolve(result.rows[0]);
    } catch (err) {
      console.log('Error occurred', err);

      reject(err);
    } finally {
      // If conn assignment worked, need to close.
      if (conn) {
        try {
          await conn.close();

          console.log('Connection closed');
        } catch (err) {
          console.log('Error closing connection', err);
        }
      }
    }
  });
}

module.exports.getEmployee = getEmployee;

查看此系列以了解更多信息: https://jsao.io/2017/06/how-to-get-use-and-close-a-db-connection-using-various-async-patterns/

【讨论】:

    【解决方案2】:

    您可以尝试将连接添加到在try-catch 块外声明的变量,如下所示:

    let connection;
    
    try {
            await oracledb.getConnection(config.db)
            .then(function (conn) {
               // this is where you assign the connection value to a variable
                connection = conn;
                return conn.execute(querys.queryTest());
            }, function(err) {
                console.log(err);
            })
            .then(function (result) {
                console.log('Query executed');
                console.log(result.rows[0]);
            }, function(err) {
                console.log(err);
            })
            .catch(function(err) {
                console.log(err);
            });
    
        } catch (error) {
            console.log(error);
        } finally {
           // this if should be fine now
            if (connection) {
                try {
                    await connection.close();
                } catch (err) {
                    console.error(err);
                }
            }
        }
    

    我建议阅读 javascript 中的作用域,它可能会帮助您解决未来的问题。这是一个链接:https://www.w3schools.com/js/js_scope.asp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 2015-11-05
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2014-08-30
      • 1970-01-01
      相关资源
      最近更新 更多