如何在等待 await 函数时每秒做一些事情?

How to do something every second while waiting for await function?

我想等待一个 await myFunction() 并且在等待 myFunction() returns 期间我想每 1 秒 console.log("1 second awaited") 一次。我尝试使用 .then() 但没有得到任何结果,也许我不善于理解承诺。

P.S.: myFunction() 获取 ajax 响应并且工作正常。

在 Promise 开始之前设置一个时间间隔,并在 Promise 解决(或拒绝,如果您愿意)后清除它:

const intervalID = setInterval(() => {
  console.log('1 second awaited');
}, 1000);
try {
  await myFunction();
} catch(e) {
  // ...
}
clearInterval(intervalId);

或者,如果 catch 也可以抛出(它可能不应该):

const intervalID = setInterval(() => {
  console.log('1 second awaited');
}, 1000);
try {
  await myFunction();
} catch(e) {
  // ...
} finally {
  clearInterval(intervalId);
}

如果没有 await 可能会更好看:

const intervalID = setInterval(() => {
  console.log('1 second awaited');
}, 1000);
myFunction()
  .catch(handleErrors) // either make sure handleErrors doesn't throw, or catch again
  .then(() => {
    clearInterval(intervalId);
  });