【问题标题】:Repeat this set of actions forever in node.js在 node.js 中永远重复这组操作
【发布时间】:2016-12-26 02:17:22
【问题描述】:

我正在使用 node.js。我有这个函数,它使用承诺在执行某些操作之间引入延迟。

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)

编辑:我开始悬赏使用重复队列来解决问题的答案。

【问题讨论】:

  • 您的示例显示了异步行为,然后您使用了同步这个词,这是不可能的。
  • 谢谢。相应地更改了问题的详细信息。
  • 看到评论并重新阅读问题。您可能应该使用的是重复队列,而不是承诺。长时间延迟的无限循环的性能可能不是什么大问题,但 Promise 有很多队列不需要的额外开销。
  • 我怀疑你在这里解决了错误的问题——你的代码实际上在做什么?有比编写这样的代码更好的作业调度工具。

标签: node.js asynchronous promise


【解决方案1】:

只使用递归

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) => { ... });
}

【讨论】:

  • 如果 do_X 或 do_Y 抛出会发生什么?
【解决方案2】:
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) => { ... });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多