module.exports.report.logon 不是函数

module.exports.report.logon is not a function

我试图让登录名在调度程序上工作,但收到 module.exports.report.logon is not a function 错误。这是代码:

const cron = require('node-cron');
const cms = require("g4js-cognos").Cms;
module.exports.report = new cms(url, namespace, usr, psw);

let task = cron.schedule('*/1 * * * *', function() {
    logonToCognos();
}, true);

task.start();

function logonToCognos() {
    module.exports.report.logon().then((response) => {  // THE ERROR
        console.log(" LOGGED on, status: " + response.statusCode);
    }).catch((error) => {
        console.log(" Logon on fail: " + error);
    });
}

当我不使用 scheduller 并且 module.exports.report 在函数之外时,一切正常:

const cms = require("g4js-cognos").Cms;
module.exports.report = new cms(url, namespace, usr, psw);

module.exports.report.logon().then((response) => {
    console.log(" LOGGED on, status: " + response.statusCode);
}).catch((error) => {
    console.log(" Logon on fail: " + error);
});

此外,如果我不使用 module.exports,它工作正常(但我必须使用导出,因为我在另一个模块中需要它):

const cms = require("g4js-cognos").Cms;
const report = new cms(url, namespace, usr, psw);

let task = cron.schedule('*/1 * * * *', function() {
    logonToCognos();
}, true);

task.start();

function logonToCognos() {
    report.logon().then((response) => {  // NO ERROR
        console.log(" LOGGED on, status: " + response.statusCode);
    }).catch((error) => {
        console.log(" Logon on fail: " + error);
    });
}

有什么想法吗?为什么 module.exports 的工作方式如此不同?谢谢。

尝试注入 module.exports.report:

    const cron = require('node-cron');
    const cms = require("g4js-cognos").Cms;
    module.exports.report = new cms(url, namespace, usr, psw);

    let task = cron.schedule('*/1 * * * *', function() {
        logonToCognos(module.exports.report);
    }, true);

    task.start();

    function logonToCognos(report) {
        report.logon().then((response) => {  // THE ERROR
            console.log(" LOGGED on, status: " + response.statusCode);
        }).catch((error) => {
            console.log(" Logon on fail: " + error);
        });
  }

试试这个:

const cron = require('node-cron');
const cms = require("g4js-cognos").Cms;

// init your class
const report = new cms(url, namespace, usr, psw);

// define what to do after logon
report.logon().then((response) => { 
  console.log(" LOGGED on, status: " + response.statusCode);
}).catch((error) => {
  console.log(" Logon on fail: " + error);
});

// define cron job
const task = cron.schedule('*/1 * * * *', function() {
  report.logon();
}, true);

// start cron job
task.start();

// finally export your class
module.exports.report = report;

也许这对你有帮助module.exports