【发布时间】:2017-07-04 16:54:57
【问题描述】:
我在打字稿中有一段代码有一个非常奇怪的行为 我写了一些显然没问题的代码,但我有一个非常奇怪的行为。 登录到服务后,我想启动 CronJob。
SomeService.login()
.then(() => {
// new CronJob(expression, workFunction, null, true);
workFunction();
});
function workFunction() {
console.log("start")
Promise.resolve()
.then(() => startSomething())
.then(moreStuff1)
.then(moreStuff2)
.then(moreStuff3)
...
.then(console.log)
.catch(errorHandling);
}
如果我像现在一样调用workFunction,这段代码对我来说很好,但是如果我切换代码以使用CronJob,它会调用该函数,但里面的promise不会被解析。 第一个 .then 被调用,下一个被忽略,函数 startSomething() 的返回将打印在最后一个 .then()
我不知道这是否与 CronJob 是从 Promise.then() 内部启动的事实有关,但我看到 workFunction 在每次滴答时都被调用,这是正确的。
已修复
我可以通过将 workFunction 绑定到 this 来修复它。
new CronJob(expression, workFunction.bind(self), null, true);
【问题讨论】:
-
我曾经遇到过类似的问题,因为缺少环境变量。检查:askubuntu.com/questions/23009/reasons-why-crontab-does-not-work 和 2clickfix.com/6-reasons-cron-job-not-running
-
顺便说一句...
Promise.resolve() .then(() => startSomething()).then(...只是startSomething().then(...
标签: javascript typescript cron promise