javascriptasync-await

Is there a way to use Await to wait until a condition returns true?


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!


Solution

  • 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');
    })();