在node.js中无限重复执行这组操作

6

我正在使用node.js。我有一个使用promise的函数,用于在执行某些操作之间引入延迟。

function do_consecutive_action() {
    Promise.resolve()
        .then(() => do_X() )
        .then(() => Delay(1000))
        .then(() => do_Y())
        .then(() => Delay(1000))
        .then(() => do_X())
        .then(() => Delay(1000))
        .then(() => do_Y())
    ;
}

我想要做的是让这组操作永久重复。在node.js中,如何实现此功能?
//make following actions repeat forever
do_X() 
Delay(1000)
do_Y()
Delay(1000)

编辑:我开始设置了一份赏金,用于回答使用重复队列解决问题的答案。


1
你的例子展示了异步行为,然后你使用了同步这个词,这是不可能的。 - zzzzBov
谢谢。已根据要求修改了问题的详细信息。 - user6064424
看到了评论并重新阅读了问题。你应该使用的是重复队列,而不是 promises。在具有长延迟的无限循环上的性能可能并不重要,但 promises 有许多额外的开销,而队列则不需要。 - zzzzBov
我怀疑你在解决错误的问题 - 你的代码实际上在做什么?有比编写这样的代码更好的工具来进行作业调度。 - Benjamin Gruenbaum
2个回答

3
只需使用递归。
function do_consecutive_action() {
    Promise.resolve()
        .then(() => do_X() )
        .then(() => Delay(1000))
        .then(() => do_Y())
        .then(() => Delay(1000))
        .then(() => do_consecutive_action())
        // You will also want to include a catch handler if an error happens
        .catch((err) => { ... });
}

1
如果 do_X 或 do_Y 抛出异常会发生什么? - Benjamin Gruenbaum

0
function cb(func) {
   try {
       func();
   }
   catch (e) {
      do_consecutive_action();
   }
}

function do_consecutive_action() {
Promise.resolve()
    .then(() => cb(do_X))
    .then(() => Delay(1000))
    .then(() => cb(do_Y))
    .then(() => Delay(1000))
    .then(() => do_consecutive_action())
    // You will also want to include a catch handler if an error happens
    .catch((err) => { ... });

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接