0

I'm looping over this url /api?id=1&page= every time requesting a different page until i get the result i want.

I can't figure out how and why i can't stop the loop from within the request.

async something() {

  let results = []
  for (let i = 0;i < 999;i++) {
    await rp('/api?id=1page='+i).then(string => {
     results.push(string)
     if(results === 'THE END') {
        // break here
     }
    })
  }
  Promise.all(results).then(res => {
   // do something
  })
}
JiPaix
  • 69
  • 1
  • 8

2 Answers2

1

You can only break from a loop when the loop is inside the current function. If the loop is outside the function (eg, a .then callback), you can't break out of it.

Instead of using .then, assign the awaited string to a variable and check it (and make sure to check the string against 'THE END', not the results array):

async something() {
  const results = [];
  for (let i = 0;i < 999;i++) {;
    const string = await rp('/api?id=1page='+i);
    results.push(string);
    if(string === 'THE END') {
      break;
    }
  }
  // do something with results
}

Note that since you're pushing the resolved values themselves to the results array, there's no need to call Promise.all on the array.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

considering that rp is the function that request your url, this is the simplest answer i can come up with.

let results = []
  for (let i = 0;i < 999;i++) {//if i is greater than or equal 999, the loop will end
    await rp('/api?id=1page='+i).then(string => {
     results.push(string)
     if(results === 'THE END') {
        //do stuffs you need to do
        // break here
        i = 1000;
     }
    })
  }
artX
  • 121
  • 4