Unable to run the same request multiple times

Can anyone tell me why this code won’t run the same GET request multiple times based on the ‘if’ condition? It just runs once and then stops. This request is part of a workflow. I am unable to find anything wrong with this code.

const maxNumberOfTries = 3; // your max number of tries

const sleepBetweenTries = 6000; // your interval between attempts

if (!pm.environment.get("tries")) {

    pm.environment.set("tries", 1);

}

console.log("Retries " + pm.environment.get("tries") + " of " + maxNumberOfTries);

if (pm.environment.get("tries") < maxNumberOfTries) {

    const tries = parseInt(pm.environment.get("tries"), 10);

    pm.environment.set("tries", tries + 1);

    setTimeout(function () {}, sleepBetweenTries);

    postman.setNextRequest(pm.info.requestName);

    } else {

  

    pm.test("Status code is 200", function () {

        pm.response.to.have.status(200);

    });    

}

Hey @oasis, how are you running the collection?

This should work fine in Runner https://learning.postman.com/docs/running-collections/intro-to-collection-runs/ or by using newman on CLI .

Also, for setTimeout() - you would need to explicitly use setInterval for it to work, check out these resources:

Cheers

1 Like

Hi @amit, I have 4 requests in a folder. I choose the folder in the collection runner. This request is the 3rd one. All prev requests run fine and when it comes to this one, it gets executed once(the very first) as it was behaving previously. And since I have declared setTimeout() explicitly it seems to be waiting there for ever now.

Though it prints “I am here”, it doesn’t seem to be running postman.setNextRequest(pm.infor.requestName). I can’t see it running at all in the console.

This is all I have in the console:-

Hi @amit, I think I have found the issue. I had another setNextRequest to run the 4th request as you can see in the above screenshot. I moved that to the ‘else’ and it runs fine now. I fail to understand how setNextRequest works sometimes:)

Thanks for your help.

Hi,
I see that you have found a solution already. If you need more examples about retries you can check those code snippets here

Cheers :slight_smile:

1 Like

Thanks @michal.robaszewski.j, that’s really useful