Javascript wait for condition to be true using promises

Viewed 12827

I am struggling to make a simple waiting function in my program. I want to use promises and async await if possible. What I have so far:

 function waitForCondition(conditionObj) {
   var start_time = new Date().getTime()

   function checkFlag() {
     if (conditionObj.arg == conditionObj.test) {
       console.log('met');
       return new Promise(resolve => setTimeout(resolve, 1));
     } else if (new Date() > start_time + 3000) {
       console.log('not met, time out');
       return new Promise(resolve => setTimeout(resolve, 1));
     } else {
       window.setTimeout(checkFlag, 1000); 
     }
   }
   checkFlag();
 }

  async function run() {
    console.log('before');
    await waitForCondition({arg: '1', test: '1'})
    console.log('after');
  }
  run();

It should check every 1 second for a maximum time of 3 seconds. The console should look like this:

'before'
'met'
'after'
3 Answers
Related