在node.js中永远重复这一组操作
我正在使用node.js 我有这个function,它使用承诺在执行某些操作之间引入延迟。
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)
编辑:我开始赏金的答案,使用重复队列来解决问题。
只要使用recursion
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) => { ... }); }
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) => { ... });
}