0

我正在尝试编写可重用函数以从 oracledb 获取值并在需要时分配该值。

我的示例代码如下。//getTtalRwCnt.js

'use strict';
var db_con = require('./oracleConnectPage.js');
// var db = new db_con();
var OracelQP = db_con.getOracleQP_details();
var oracledb = require('oracledb');
var tmpRwCnt;

var getTtalRwCnt = function () {
    oracledb.outFormat = oracledb.ARRAY;
    var query = "SELECT TESTCASEID FROM EXECUTE_TESTCASE";
    oracledb.getConnection(OracelQP, function (err, connection) {
        if (err) {
            console.error(err.message); return;
        }
        connection.execute(query, function (err, result) {
            if (err) {
                console.error(err.message); 
                connection.close();
                return;
            }
            console.log("result----->" + result.rows.length);
            tmpRwCnt = result.rows.length;
            return tmpRwCnt;
        })
    })
}
module.exports.getTtalRwCnt = getTtalRwCnt();

//spec.js

    'use strict';
var rwCnt = require('../DBSample/DB/getTtalRwCnt.js');

describe('Get Total number of Rows from DB', function () {
  it('Get Rw count',function(){
    console.log(rwCnt.getTtalRwCnt());
  });
});
4

1 回答 1

1

您的代码中有两个问题:

1)导出错误

module.exports.getTtalRwCnt = getTtalRwCnt();

应该

module.exports.getTtalRwCnt = getTtalRwCnt;

2) tmpRwCnt是回调函数的返回值,而不是函数的返回值getTtalRwCnt,另外你没有函数的返回值getTtalRwCnt

要使回调函数中的值可以在回调之外使用,您可以选择使用 Promise 解决方案。

'use strict';
var db_con = require('./oracleConnectPage.js');
// var db = new db_con();
var OracelQP = db_con.getOracleQP_details();
var oracledb = require('oracledb');

var getTtalRwCnt = function () {
    return new Promise(function(resolve, reject){
        oracledb.outFormat = oracledb.ARRAY;
        var query = "SELECT TESTCASEID FROM EXECUTE_TESTCASE";
        oracledb.getConnection(OracelQP, function (err, connection) {
            if (err) {
                console.error(err.message);
                reject(err);
            }
            connection.execute(query, function (err, result) {
                if (err) {
                    console.error(err.message); 
                    connection.close();
                    reject(err);
                }
                rwCnt = result.rows.length;
                console.log("result----->" + rwCnt);
                resolve(rwCnt);
            })
        })
    });

};

module.exports = getTtalRwCnt;

//spec.js

'use strict';
var getTtalRwCnt = require('../DBSample/DB/getTtalRwCnt.js');

describe('Get Total number of Rows from DB', function () {
  it('Get Rw count',function(){
    var totalRw = getTtalRwCnt();

    // If you use Jasmine or Chai
    totalRw.then(function(total){
        console.log('total row: ' + total);
        expect(total).toEqual(10);
    });

    // if you use Jasmine 
    expect(totalRw).toEqual(10);

    // if you use Chai and Chai-as-promise
    expect(totalRw).to.eventually.to.equal(10);
  });
});
于 2018-01-25T14:29:04.180 回答