0

I was working on something, and I was thinking about if I could use await() to wait until a condition returns true. Possibly something like this: await(x===true);

I don't know if you can do this, but it would be very helpful if you could! Is this possible, or no? Thank you!

  • JS doesn't work this way – Ken Bekov Jun 06 '23 at 22:49
  • see: [Polling until getting specific result?](https://stackoverflow.com/questions/46208031/polling-until-getting-specific-result) or [Promise to async await when polling](https://stackoverflow.com/questions/57213034/promise-to-async-await-when-polling) or [can async with fetch poll until a condition is met?](https://stackoverflow.com/questions/64130475/can-async-with-fetch-poll-until-a-condition-is-met-survive-rejection) – pilchard Jun 06 '23 at 23:02
  • And linked article in duplicate [Polling with async/await](https://dev.to/jakubkoci/polling-with-async-await-25p4) – pilchard Jun 06 '23 at 23:05
  • Do you really want to block the main thread until that condition becomes true? In most cases, the answer should be no; instead, create and fire an event. – InSync Jun 07 '23 at 02:19

1 Answers1

3

You can implement a busy wait like this:

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');
})();  
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • 3
    You can, but you absolutely shouldn't. – Bergi Jun 06 '23 at 23:12
  • why shouldn't you? – Cerric Liadon Jun 07 '23 at 00:53
  • @CerricLiadon It would be much better to subscribe to a certain event, and to create a mechanism that fires the event when something changes. – Andrew Parks Jun 07 '23 at 01:13
  • @CerricLiadon you should invert the question and ask why you would need to do something like this in the first place? It is incredibly rare to have a valid use case for doing it so and in that virtually non-existent scenario something else is usually dreadfully wrong. – Aluan Haddad Jun 07 '23 at 01:23