Conditional API call based on response from an earlier API call - Collection runner

I have three APIs. API#1, API#2, API#3
API#1 returns names e.g. {{endPoint}}/GetNames
API#2 returns phone number(s) for a particular name e.g. {{endPoint}}/GetPhoneNo/{{name}}
API#3 returns carrier names for a particular phone number e.g. {{endPoint}}/GetCarrier/{{phoneNo}}
I get an array of names from API#1 response body. I store them in an environment variable nameArray in the Tests script of API#1

Tests of API#1

pm.variables.set("nameArray", pm.response.json().names);
pm.variables.set("phoneNoArray", []);

I use the nameArray in Pre-request Script of API#2 to call API#2 on a per name basis. Then in the Tests Script of API#2, I populate phoneNoArray from the response body of API#2.

Pre-request Script of API#2

if(nameArray.length){
    pm.variables.set("name", nameArray.shift());
    postman.setNextRequest(pm.info.requestName);
}

Tests of API#2

pm.variables.get("phoneNoArray").push(pm.response.json().phoneNo);

Now, there could be a scenario where, none of the names have a phone number i.e. phoneNoArray is empty. In this case I don’t want to call API#3 as it would be an invalid call. So I have the following

Pre-request Script of API#3

if(phoneNoArray.length){
    pm.variables.set("phoneNo", phoneNoArray.shift());  
    postman.setNextRequest(pm.info.requestName);
}
else{
    //If there are no phone numbers, do not call API#3
    postman.setNextRequest();
}

This obviously doesn’t work because it would make one call to API#3 as we can’t skip call to API#3 when the checking condition is itself in Pre-request Script of API#3. The check needs to be in API#2. I am not sure how do I put the check in API#2 as it runs in a loop.

If you do get to the scenario when none of the names have a phone number, you can actually call something like

postman.setNextRequest(null);

which should terminate the program. According to this documentation Conditional Workflows in Postman | Postman Blog
You may want to call that in your API#2

@francisadvlighting

No you can’t as setNextRequest() just sets the next request to run after current request and all of the code in the pre-request script and tests tab have completed.

So as the original poster stated, it will still run at least once.

However, things have moved on since the original query, and Postman now has a skip request feature.

The New Skip Request Feature - :newspaper: Postman News - Postman Community