Breaking out of loops

  1. My goal: I want to be able to break out of a loop once a certain condition is met
  2. Issue: Right now I have using the Response block because I thought that's how we can break out of a loop in a retool workflow. However, it seems like the loop is still going.
  3. Steps I've taken to troubleshoot:
  4. Additional info: (Cloud or Self-hosted, Screenshots):
    Evidence that it is not breaking out of loop:

Hi @Sharon_Alexander,

It might be easier to use a JavaScript block as it can offer more control than a Loop block in many cases, especially when you're trying to break out early based on dynamic conditions like data.length === 0.

Something like this should get you started.

let page = 1;
let allResults = [];

while (true) {
  const response = await runBlock('getSites', {
    page,
    results: 20
  });

  const data = response?.data || [];

  if (data.length === 0) {
    console.log("No more data, breaking loop.");
    break;
  }

  allResults.push(...data);
  page++;
}

return allResults;

Let me know if you need more help!

2 Likes

Thanks again for joining office hours, @Sharon_Alexander! Lacking a true mutable global variable, I agree with @Shawn_Optipath that coordinating your loop via a JS block is probably the best workaround. While the method that we discussed towards the end of office hours - and described here - does work, you've already noticed that it has some drawbacks.

Let us know if you have any specific questions about implementing something like what's shown above! I'll follow up on the status of the relevant feature request internally. :+1: