Loop a post request

Hello, I’m trying to figure out the logic for looping a request:
I have a post request, that would use data from an array created in a previous request:
array = [data1, data2, data3, data4]

So I have a ‘For’ cycle, similar to :

    for (i = 0; i < array.length; i ++){
    let userData = array[i] }

I’m using data-raw json for the request, so the idea is to loop it so that it runs the request once for each index of the array, so first run would be userData - data1, and then again with data2 and so on.

I’ve tried to add - I’m working on it as am creating this post, but need help

if (array.length === i) {
    console.log('done');
    return;
}
postman.setNextRequest('myRequest');

This is my current attempt:

var index1 = parseInt(postman.getEnvironmentVariable('index1'));
var profileArrayID = postman.getEnvironmentVariable('profileArrayID');
var organizationArrayID = postman.getEnvironmentVariable('organizationArrayID');

index1 = index1 + 1;
let userId = profileArrayID[index1];
let organisationId = organizationArrayID[index1];

if (profileArrayID.length === index1){
    console.log("Array done");
    return;
    
}
pm.environment.set("userId", userId);
pm.environment.set("organisationId", organisationId);
postman.setNextRequest('randomizedSignUps');

However it just runs the array by default value of index, aka array[index] with index being 0, how do I get it to get the index to be index = index + 1 for each request run, so first time 0, then 1, then 2 until the array.length is equal to the index

Last edit It seems I got it working, had to update environment for index1, so currently I have index1 = -1 in the environment, also having profileArray.length === index1 - 1, as it lead to having 1 duplicate post without the ‘-1’ , anyway it all seems to work well - as intended with the exception that there is 1 more request which fails as it has ran through the array and seems to try to use undefined value.

So in the end, once the array.length = index (without -1), the nextRequest stops running, however it runs one last time, making a duplicate entry

@theToncheff in this other post you can find one way to solve your problem, I guess!

Look out and see if fits you!

:sunglasses:

I don’t seem to be able to make it work with that either.
Basically it works halfway either my way or the way you offered, once it runs the last index of the array, it returns and stops the nextRequest, however it tries to run one last time, giving me a 500 error as there is nothing to get from the array. I’m trying to get it not to run that last request, but fail to do so.

edit Could it be because everything is in the prerequest script?

It could be, why dont you try to do all of this on Tests?

@theToncheff

Here’s an example Collection I threw together with a looped POST request:

Redacted: wrong link. Will repost soon.

1 Like

Sorry @theToncheff , wrong link. Here’s the correct one: