async 函数作为 setInterval nodejs 的参数

async function as argument to setInterval nodejs

当我将一个异步函数作为参数传递给 setInterval 时,它有一个奇怪的行为:它工作了几次但随后毫无例外地停止了。

setInterval(() => doSomethingAsync(), 1000);

我不知道为什么。

我尝试实现自己的 setIntervalAsync 但行为是一样的:

const sleep = ms => new Promise(res => setTimeout(res, ms));

const setIntervalAsync = async (func, interval) => {
  while (true) {
    await func();
    await sleep(interval);
  }
};

// schedule it
setIntervalAsync(async () => await doSomethingAsync(), 1000);

问题出在别处,与 setInterval 或我的回调完全无关。

setInterval 与异步函数一起工作正常。