我的 typescript 中有一段代码,其行为非常奇怪 我写了一些代码,显然没问题,但我有一个非常奇怪的行为。 登录到服务后,我想启动 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 被调用,接下来的 .then 被忽略,函数 startSomething() 的返回结果将打印在最后一个 .then()
我不知道这是否与 CronJob 从 Promise.then() 内部启动这一事实有关,但我看到每次更新都会调用 workFunction,这是正确的。
已修复
我可以通过将 workFunction 绑定(bind)到此来修复它。
new CronJob(expression, workFunction.bind(self), null, true);
最佳答案
这种行为似乎与 cron 作业的执行上下文有关。我不明白,但似乎在某些方面有所不同。我想通过超时打破这个上下文可以解决问题:
function wrapper() { setTimeout(workFunction) }
new CronJob(expression, wrapper, null, true);
关于javascript - cron 作业内的 Promise 未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42259390/