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!