How to execute code in order in a while loop in Javascript?

Viewed 111

I'm trying to run some JavaScript code on Postman, but I can't find a way for it to run in the order that I need. This is what I'm trying to do:

  • Retrieve the API response and verify if the "pending" array contains any item
  • If id does, I'll save the id of the record (orderId) in an environment variable to use in my actual request
  • At this point I would set found = true and break the loop when it leaves the setTimout function

Note: I created the function to introduce 400ms delay between the attempts, as it will allow the pending array to be populated

    var found = false;
    var counter = 0;

    while (counter < 10) {

        setTimeout(async () => {
            var size = await response.json().pending.length;

            if (size > 0) {
                var orderId = response.json().pending[0].orderId;
                pm.environment.set("current_order", orderId);
                found = true;
            }
        }, [400]);

        console.log(found);
        if (found) { break; }

        counter++;
    }

My problem is that the part that is outside the setTimeout function executes first, so it will never satisfy the condition "If (found)". It always executes the code 10 times, even if the record is found in the first attempt.

My question is: How can I write it in order to check if the record was found after each attempt and break from the loop if positive?

Thanks!

1 Answers

As suggested above, you might be able to solve this issue with a simpler recursive function. An example on how it would look:

var found = false;
var size = 0;

async function checkResponse() {
  var size = await response.json().pending.length;

  if (size > 0) {
    var orderId = await response.json().pending[0].orderId;
    pm.environment.set('current_order', orderId);
    found = true;
  }
  if (!found) {
    await checkResponse();
  }
}

await checkResponse();

Here is a synchronous test for the logic above:
var found = false;
// var size = 0;
var size = -5;

function checkResponse() {
  // var size = await response.json().pending.length;
  size += 1;
  console.log(size);

  if (size > 0) {
    // var orderId = response.json().pending[0].orderId;
    // pm.environment.set('current_order', orderId);
    console.log("pm.environment.set('current_order', orderId);");
    found = true;
  }
  console.log('END?');
  console.log(found);
  if (!found) {
    checkResponse();
    console.log('checkResponse();');
  }
}

checkResponse();

Output:

-4
END?
false
-3
END?
false
-2
END?
false
-1
END?
false
0
END?
false
1
pm.environment.set('current_order', orderId);
END?
true
checkResponse();
checkResponse();
checkResponse();
checkResponse();
checkResponse();
Related