Javascript 更改for循环中迭代器的数目

Javascript 更改for循环中迭代器的数目,javascript,Javascript,我想有条件地打破这样的循环 for(let i = 0; i < 3; i++) { exampleFunction().then(result => { res = 0 ? i = 3 : null }) } for(设i=0;i{ res=0?i=3:null }) } 我希望exampleFunction至少运行3次,除非它得到所需的结果,在这种情况下,我希望它停止运行 exampleFunction异步运行。让它工作的唯一方法是使用async/await c

我想有条件地打破这样的循环

for(let i = 0; i < 3; i++) {
 exampleFunction().then(result => {
    res = 0 ? i = 3 : null
 })
}
for(设i=0;i<3;i++){
exampleFunction()。然后(结果=>{
res=0?i=3:null
})
}

我希望
exampleFunction
至少运行3次,除非它得到所需的结果,在这种情况下,我希望它停止运行

exampleFunction
异步运行。让它工作的唯一方法是使用
async/await

const iterateWithExampleFunction=async()=>{
for(设i=0;i<3;i++){
console.log('before',i)
等待exampleFunction()。然后(结果=>{
i=结果===0?3:i;
});
console.log('after',i)
}
};
const exampleFunction=async()=>{
返回0;
}

迭代示例函数()
示例函数
异步运行。让它工作的唯一方法是使用
async/await

const iterateWithExampleFunction=async()=>{
for(设i=0;i<3;i++){
console.log('before',i)
等待exampleFunction()。然后(结果=>{
i=结果===0?3:i;
});
console.log('after',i)
}
};
const exampleFunction=async()=>{
返回0;
}

迭代示例函数()您可以对外部作用域进行计数,然后执行异步调用

let count = 0;

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

您可以对外部作用域进行计数,然后执行异步调用

let count = 0;

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

只需等待
结果,而不必中断

(async function() {
  for(let i = 0; i < 3; i++) {
   const result =  await exampleFunction();
   if(result === 0) break;
  }
})();
(异步函数(){
for(设i=0;i<3;i++){
const result=await exampleFunction();
如果(结果==0)中断;
}
})();

只是
等待
结果,而不是
中断

(async function() {
  for(let i = 0; i < 3; i++) {
   const result =  await exampleFunction();
   if(result === 0) break;
  }
})();
(异步函数(){
for(设i=0;i<3;i++){
const result=await exampleFunction();
如果(结果==0)中断;
}
})();

希望这能给你一些想法

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);

希望这能给你一些想法

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);

let result=wait exampleFunction();如果(结果==0)中断
let result=wait exampleFunction();如果(结果==0)中断好的问题是它是一个异步进程,所以循环在激发()之前运行。好的问题是它是一个异步进程,所以循环在激发()之前运行。