javascript 间隔执行后的回调

javascript callback after the interval has executed

我正在使用自定义间隔函数来确保函数执行先完成,直到下一次 运行。通常我会执行以下操作我检查 redis 数据库并检查作业是否由 sidekiq 执行。如果它被执行,我向数据库发出请求以获取信息,如果它被写入它,我 运行 这个函数 10 次如果在第 10 次之后没有数据我解析未定义。我想知道我现在的解决方案是否可以以某种方式改进。

 const interval = (func, wait, times) => {
    const interv = function(w, t){
      return () => {
        if (typeof t === 'undefined' || t-- > 0) {
          setTimeout(interv, w);
          try {
            func.call(null);
          }
          catch (e) {
            t = 0;
            throw e.toString();
          }
        }
      };
    }(wait, times);
    setTimeout(interv, wait);
  };

    let intervalCount = 0;
    interval(() => {
      intervalCount++;
      redisClient.lrange('queue:default', 0, -1, (err, results) => {
        const job = results.find((element) => { return JSON.parse(element).jid === jobId; });
        if (job === undefined) {
          checkDatabase(personId).then((result) => {
            if (result) {
              resolve(checkDatabase(personId));
            } else if (intervalCount >= 10) {
              resolve(undefined);
            }
          });
        }
      });
    }, 1500, 10);

嗯,您使用的是现代 NodeJS,并且您提到您使用的是 promises 和 bluebird,所以让我们使用使用生成器和 bluebird 的现代解决方案。

您根本不应该经常使用 promise 构造函数。您可以承诺 redis API 让您的生活更轻松:

Promise.promisifyAll(require("redis")); // now redis is promisified


var pollAndResolve = Promise.coroutine(function* pollAndResolve () {
    for(var i = 0; i < 10; i++) {
       yield Promise.delay(1500); // wait 1500 ms
       yield redisClient.lrangeAsync('queue:default', 0, -1); // since we promisifed
       const job = results.find((element) => JSON.parse(element).jid === jobId);
       if (result) return yield checkDatabase(personId);
    }
});