2016-11-28 21 views
0

我試圖讓登錄工作在調度程序上,但得到了module.exports.report.logon is not a function錯誤。這是代碼:module.exports.report.logon不是函數

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工作如此不同?謝謝。

+0

可能有事情做與範圍。你在函數logonToCognos的範圍內,所以模塊可能沒有定義。你有沒有嘗試傳遞構造的cms作爲函數的參數? – kriddy800

+0

如果,而不是module.exports.report,我把const報告,那麼它工作正常。爲什麼module.export表現如此不同? – ljerka

+0

我編輯了這個問題也有這個例子。 – ljerka

回答

1

試試這個:

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

0

嘗試注入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); 
     }); 
    } 
+0

得到「report.logon不是一個函數」 – ljerka