有没有办法使用Await来等待条件返回true?

问题描述 投票:0回答:2

我正在做一些事情,我正在考虑是否可以使用await()来等待条件返回true。可能是这样的:

await(x===true);

我不知道你是否能做到这一点,但如果你能做到的话,那就非常有帮助了! 这可能吗?还是不可能? 谢谢!

javascript async-await
2个回答
4
投票

你可以像这样实现繁忙等待:

console.log('begin');

async function busyWait(test) {
  const delayMs = 500;
  while(!test()) await new Promise(resolve => setTimeout(resolve, delayMs));
}

let a = 'hello';
setTimeout(() => a = 'world', 2000);

(async () => {
  await busyWait(() => a==='world')
  console.log('done');
})();  


0
投票

更通用的方法是我最近编写的一个函数。

async function waitUntilTrue(
  conditionFunction: () => boolean,
  interval = 10,
  timeout = 10000,
  throwOnTimeout = false
) {
  let timePassed = 0;
  return new Promise<void>(function poll(resolve, reject) {
    if (timePassed >= timeout) {
      return throwOnTimeout ? reject() : resolve();
    }
    if (conditionFunction()) {
      return resolve();
    }
    timePassed += interval;
    setTimeout(() => poll(resolve, reject), interval);
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.