Skip to content
Advertisement

I try to make a while loop in javascript. I have example of what i’m trying to do in body

const condition = true;
while (condition) condition = checkCondition();

function checkCondition(){
    (async () => {
        if (await page.$('condition') !== null){ // condition met
            return true;
        } else { // condition not met
            return false;
        }
    })();
}

I’m not sure if I am doing it right. Please can someone show me the right way.

Advertisement

Answer

prime’s answer will bring you closer and provides some useful material to read up on. I though I would build on it a bit by fixing a couple issues and adding some more explanation.

Below is a working demonstration of your code

(async function() {
  let condition = true;
  while (condition) condition = await checkCondition();
})()

async function checkCondition() {
  console.log('checkCondition was called');
  if (await someAsyncLogic() !== null){ // condition met
    return true;
  } else { // condition not met
    return false;
  }
}

async function someAsyncLogic() {
  return Math.random() > 0.2 ? true : null;
}

Your code effectively had the following:

function checkCondition(){
    (async () => {
        // do some logic
        return true/false
    })();
}

What’s wrong here is that your return true/false is just going to make your inner IIFE (async () => ...)() provide a promise that resolve to true/false. You could even store that value in a variable if you cared.

function checkCondition(){
    const theResult = (async () => {
        // do some logic
        return true/false
    })();
    console.log(theResult) // <-- [object Promise]
    console.log(await theResult) // <-- true/false
}

But, as we can see, checkCondition itself doesn’t return anything. Only the inner function inside does. You would have to return theResult to do so – but in order to do that, you would need to declare checkCondition as an async function, at which point, there’s no need for your async IIFE anymore, which is why that example takes it out.

If checkCondition is async, then the code calling it has to use await, and has to be withing an async context (like an async IIFE, or a normal async function).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement