How can I poll a request in Postman until a task reaches "Successful" or "Failed" status?

I’m trying to use Postman to test a two-step API process:

  1. The first request creates a task and returns a taskId.
  2. The second request checks the status of that task using the taskId.

The possible status responses are:

  • "InProgress" — task is still running.
  • "Successful" — task completed successfully.
  • "Failed" — task failed.

It typically takes 10–20 seconds for the task to reach "Successful" or "Failed" status, so I need to poll the second request repeatedly until I get one of those two statuses.

However, Postman doesn’t work as expected in the collection runner.

My Goal:

I want to loop/poll the second request (e.g., every 3 seconds) until the status is either "Successful" or "Failed", and then stop polling and continue to the next request in the collection.

Question:

How can I implement a polling mechanism in Postman Collection Runner to repeatedly check task status every few seconds until it’s “Successful” or “Failed”, and then proceed?

You can try using something like the below code snippet:

if (jsonResponse !== null && jsonResponse.hasOwnProperty("message") && ["Successful", "Failed"].includes(jsonResponse.message.toLowerCase())) {
        console.log("Status reached:", jsonResponse.message);
        // Perform further actions if needed
    } else {
        console.log("Current status:", jsonResponse.message);
        // Increment counter
        counter++;
        // Check if counter exceeds the limit
        if (counter > 10) {
            console.log("Exiting test execution as it is taking too long to execute");
            return;
        }
        // Wait for some time before polling again
        setTimeout(pollStatus, 50000); // 5-second delay, adjust as needed
    }

That could have been awesome but it does not work …

I tried :

pm.test("Delay",function () { 
 SetTimeout(pm.expect(response.status).to.eql("Successful"),5000)
})

That also not working

And other solutions found on stack overflow nor the approach suggested on your side
https://stackoverflow.com/questions/43295102/postman-how-to-loop-request-until-i-get-a-specific-response

For me, this worked when I am triggering my querysurge test execution via api and it is waiting for execution to complete before importing the result into jira xray

A while back I shared a method using the Collection Runner that might be adapted here, it was a different context and a few years ago so it’s not going to be a straight copy and paste solution.

The code from @jyotiag-tae appears to be incomplete.

It will only wait for five seconds. I can’t see any loop in there.

You will need to use setNextRequest to actually loop and re-run the same request.

The important part here is that you have some sort of counter to ensure that it can’t loop indefinitely. I can’t emphasize that aspect enough.

The first answer on the Stackoverflow link you provided seems like it should work.

However, the code is from 2019 so there will be certain things that need to be updated.

For example, its now “pm.execution.setNextRequest” instead of “postman.setNextRequest”.

I tried that but then the runner of the whole collection/ folder would get stuck and would stop on that request, not continuing to the next request

Can you please share the code that you ended up with?

Please note that setNextRequest only works with the Collection Runner.

Here is a working example that you can consider…

As I can’t mimic your API statuses, I’ve had to be a bit creative but hopefully the logic will be the same.

I’m sending a simple request to the Postman Echo endpoint.

image

I’m mimicking the statuses in the Pre-request script.

if (typeof statuses === 'undefined' || statuses.length == 0) {
    // new run - setup statuses array
    // global variable which will persist through the collection run
    // does not need to be saved as a collection variable
    statuses = ["InProgress", "InProgress", "InProgress", "Successful", "Failed"];
    // new run - clear down existing collection variables
    pm.collectionVariables.unset("status");
}

let currentStatus = statuses.shift(); // retrieve first object from array, then delete it from the array

// set collection values from current object
// this does need to be set as a collection variable if you want to use it in the body or query parameters
pm.collectionVariables.set("status", currentStatus);

// is the collection variables set correctly?
console.log(pm.collectionVariables.get("status"));

You can pretty much ignore all of that code unless you want to use it for testing.

However based on the test data, this should loop 3 times before it hits a “Successful” status.

The Post-response script which will control the loop will look similar to the following.

const maxNumberOfTries = 3; // your max number of tries
const sleepBetweenTries = 5000; // your interval between attempts

if (typeof tries === 'undefined' || tries === null) {
    // new run - setup tries count
    // global variable which will persist through the collection run
    // does not need to be saved as a collection variable
    tries = 1;
}

// parse response
const responseStatus = pm.response.json().args.status;

// loop while status is not successful and we have not exceeded the max number of tries
if (responseStatus !== "Successful" && tries < maxNumberOfTries) {
    tries++;
    setTimeout(function () { }, sleepBetweenTries);
    currentRequest = pm.info.requestName;
    pm.execution.setNextRequest(currentRequest);
}

// no need to unset tries as it will persist through the collection run but not between collection runs

You will update as appropriate in relation to the response. I’m targeting the response elements that Postman Echo returns (which is an Echo of what was sent).

I’ve tested this. I’ve changed the maxNumberOfTries to 3, 4 & 5 and its working as expected including the timeout between each request.