Nodejs setInterval - 调用一个返回promise的函数,并执行x次延迟

时间:2018-04-23 14:12:05

标签: node.js setinterval

我无法弄清楚这一点..

我想在每次调用后多次执行一个函数。使用setInterval可以轻松实现这一点。但是,我现在正在尝试做同样的事情,但在我的setInterval代码中,我试图调用一个返回promise的函数。一旦我在setInterval中调用的函数(返回一个promise)已经完成,我只想重置我的间隔。我看不出怎么做。我的代码如下:

var repeatXTimes = config.repeatXTimes;
var sleepBetweenRepeatingAllOfTheCommandsSeconds = config.sleepBetweenRepeatingAllOfTheCommandsSeconds;
var runInfinitely = repeatXTimes == configConstants.REPEAT_INFINITE;

if (runInfinitely || repeatXTimes > 0) {

    var timesRun = 0;

    var interval = setInterval(function () {

        timesRun++;

        if (!runInfinitely && timesRun >= repeatXTimes) {       

            clearInterval(interval);
        }       

        user.runAllOfTheConfiguredCommands().then(function (respone) {

            // I only want to to set this interval to run again, once this function is complete....

        });
    }, sleepBetweenRepeatingAllOfTheCommandsSeconds * 1000););
}

请有人建议如何实现这一目标。我试过搜索但看不到解决方案。

提前致谢。

1 个答案:

答案 0 :(得分:1)

由于你的函数返回一个Promise,我相信你可以await它(语法比回调简单):

const repeatXTimes = config.repeatXTimes,
      sleepBetweenRepeatingAllOfTheCommandsSeconds = config.sleepBetweenRepeatingAllOfTheCommandsSeconds,
      runInfinitely = repeatXTimes == configConstants.REPEAT_INFINITE;

const run = async () => {
    await user.runAllOfTheConfiguredCommands()
    timesRun++
    if (runInfinitely || timesRun < repeatXTimes) setTimeout( run, sleepBetweenRepeatingAllOfTheCommandsSeconds * 1000 )
}

run()