Christopher Mellor
Christopher Mellor

Reputation: 444

change the number of the iterator in a for loop

I want to conditionally break out of a loop like this..

for(let i = 0; i < 3; i++) {
 exampleFunction().then(result => {
    res = 0 ? i = 3 : null
 })
}

I want exampleFunction to run at least 3 times unless it gets the desired result, in which case I want it to stop running.

Upvotes: 0

Views: 69

Answers (4)

hsz
hsz

Reputation: 152256

exampleFunction runs asynchronously. The only way to get it working is using async/await.

const iterateWithExampleFunction = async () => {
  for (let i = 0; i < 3; i++) {
    console.log('before', i)

    await exampleFunction().then(result => {
      i = result === 0 ? 3: i;
    });

    console.log('after', i)
  }
};

const exampleFunction = async () => {
  return 0;
}

iterateWithExampleFunction();

Upvotes: 2

Elias Toivanen
Elias Toivanen

Reputation: 848

Hopefully this gives you some ideas

async function poll(f, threshold = 3) {
  if (!threshold) {
    throw new Error("Value not found within configured amount of retries");
  }
  const result = await f();
  if (result >= 0.5) {
    return result;
  } else {
    return await poll(f, threshold - 1);
  }
}

async function task() {
  return Math.random();
}

poll(task).then(console.log).catch(console.error);

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138367

Just await the result, than break:

(async function() {
  for(let i = 0; i < 3; i++) {
   const result =  await exampleFunction();
   if(result === 0) break;
  }
})();

Upvotes: 0

Sunny Wong
Sunny Wong

Reputation: 96

You can have a count on the outer scope and then do the async call.

let count = 0;

function executeCall() {
  exampleFunction().then(result => {
    // do something with the result
    if (result !== 0 && count !== 3) {
      count += 1;
      executeCall();
    }
  });
}

Upvotes: 0

Related Questions