[英]Not able to execute callbacks in module.exports object using Node-Cron?
So I am using a module called node-cron to execute a chain of functions every night. 因此,我每天晚上使用一个名为node-cron的模块来执行一系列功能。
My function is located in another file. 我的函数位于另一个文件中。 I have added
required
that file in my app.js where the node-cron Object is located. 我已经加入
required
在我的app.js该文件在节点的cron对象所在。 That Object looks like this 该对象看起来像这样
var job = new CronJob('00 51 17 * * 0-6', savantJS.getTracksFromSavants, null, true, 'America/Los_Angeles');
This will execute the getTracksFromSavants
function in my savantJS file at 5:51pm LA time just fine. 这样会在洛杉矶时间下午5:51在我的savantJS文件中执行
getTracksFromSavants
函数,一切正常。 However the problem occurs when I try to have callback functions in my savantJS file. 但是,当我尝试在savantJS文件中具有回调函数时,就会出现问题。
For example: 例如:
module.exports = {
getTracksFromSavants: function(){
//do stuff here with arr
if(stuff happens here){
this.doNextFunction(arr)
}
},
doNextFunction: function(arr){
//do stuff
}
}
This executes the getTracksFromSavants
function fine, but once it gets to the if
it says that doNextFunction
is not defined. 该执行
getTracksFromSavants
良好的性能,但一旦它到达if
它说, doNextFunction
没有定义。
On the flip side, if I write my Cron like this: 另一方面,如果我这样编写Cron:
var job = new CronJob('00 51 17 * * 0-6', savantJS.getTracksFromSavants(), null, true, 'America/Los_Angeles');
It executes the callbacks in getTracksFromSavants()
fine. 它在
getTracksFromSavants()
执行回调。 However the issue is that when I use the ()
in the CronJob object it executes that function every time the server is started when it should only be executing it at 5:51pm. 但是问题是,当我在CronJob对象中使用
()
时,它将在服务器每次启动时执行该功能,而服务器只应在下午5:51执行该功能。
Any ideas? 有任何想法吗?
var obj = {
f: function() {
return this;
}
}
obj.f() // returns obj
var ff = obj.f;
ff(); // does not return obj - `ff` does not know the function came from `f`.
ff = ff.bind(obj);
ff(); // returns obj again
In JavaScript, calling a method using a dot notation will set this
. 在JavaScript中,使用点符号调用方法将设置
this
。 calling a method without the dot does not. 调用没有点的方法不会。 When you pass
savantJS.getTracksFromSavants
into a function, it becomes some parameter; 当您将
savantJS.getTracksFromSavants
传递给函数时,它将成为一些参数; when that parameter gets called, it does not know it has any connection to savantJS
. 当该参数被调用时,它不知道它与
savantJS
有任何连接。 Unless you bind the receiver to it. 除非您将接收器绑定到它。
Thus, you want to wrap your method call inside a normal function (that does not depend on being invoked as a method): 因此,您希望将方法调用包装在普通函数内(该函数不依赖于作为方法调用):
var job = new CronJob('00 51 17 * * 0-6', function() {
savantJS.getTracksFromSavants();
}, null, true, 'America/Los_Angeles');
Or you can bind the function to a receiver (which basically does the same thing): 或者,您可以将函数绑定到接收者(基本上做同样的事情):
var job = new CronJob('00 51 17 * * 0-6',
savantJS.getTracksFromSavants.bind(savantJS),
null, true, 'America/Los_Angeles');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.