Skip to content
Advertisement

continue a for loop outside of a promise

so let’s say I have something like this:

var x = 2;
for(var i = 0; i < 10; i++) {
   new Promise(async (resolve, reject) => {
        if(someFunctionThatChecksX(x)) {
           continue;
         }
      }
}

I can’t use continue because “jump target cannot cross function boundaries” and need a way around that to continue the for loop when that function that checks X results in true. Thanks so much for any assistance.

Advertisement

Answer

If you want the for loop to wait for the promise to resolve, put it inside of an async block. You could then use await to get the result of the promise, and continue based off that in the body of the for loop.

Altogether, it looks like this:

async function myFunction() {
    var x = 2;
    for(var i = 0; i < 10; i++) {
       let result = await new Promise(async (resolve, reject) => {
           resolve(someFunctionThatChecksX(x))
       }
       if(result) {
           continue;
       }
    }
}
Advertisement