【问题标题】:Promise inside cron job not executedcron作业中的承诺未执行
【发布时间】: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);

【问题讨论】:

标签: javascript typescript cron promise


【解决方案1】:

似乎这种行为在某种程度上与 cron 作业的执行上下文有关。我不明白,但它似乎在某些方面有所不同。我想用超时打破这个上下文可以解决问题:

function wrapper() { setTimeout(workFunction) }

new CronJob(expression, wrapper, null, true);

【讨论】:

    【解决方案2】:

    您的workFunction 中没有return 吗?

    SomeService.login()
        .then(() => {
            // new CronJob(expression, workFunction, null, true);
            workFunction();
    });
    
    function workFunction() {
        console.log("start")
    
        return Promise.resolve()
            .then(() => startSomething())
            .then(moreStuff1)
            .then(moreStuff2)
            .then(moreStuff3)
                  ...
            .then(console.log)
            .catch(errorHandling);
    }
    

    【讨论】:

    • 嗨 Alistair,workFunction 不应该返回任何东西。但我之前也尝试过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多