Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert async await in while loop to promises

I can't figure out how to convert async await functionality in a while loop to a promise based implementation.

repl showing the async await version

https://repl.it/repls/IdealisticPepperyCoding

var dependency = false;

function checkDependency() {
  return new Promise(resolve => {
    setTimeout(() => {
      dependency = true;
      return resolve();
    }, 1000)
  });
}

async function isReady() {
    while(!dependency) {
      console.log('not loaded');
      await checkDependency();
    }
    console.log('loaded')
}

isReady();
like image 967
Zack Lucky Avatar asked Jan 02 '23 17:01

Zack Lucky


1 Answers

If I'm understanding you correctly, you're wanting to use Promises without async functions instead of Promises with async functions, and the sample checkDependency may actually not set dependency = true in all cases, so you want to "loop."

Equivalent functionality could look something like this, where you "recursively" call the check function. It won't actually be recursive and lead to a stack overflow, though, since the call is done in an async callback:

var dependency = false;

function checkDependency() {
  return new Promise(resolve => {
    setTimeout(() => {
      dependency = true;
      return resolve();
    }, 1000)
  });
}

function isReady() {
  if (!dependency) {
    return checkDependency().then(isReady);
  }

  return Promise.resolve(true);
}

isReady().then(() => {
  console.log('loaded')
});
like image 93
Jacob Avatar answered Jan 05 '23 17:01

Jacob