const questions = ["what is RAM?", "what is Adobe?"];
for (let i = 0; i < questions.length; i++) {
const current_question = questions[i];
console.log(current_question);
pm.environment.set("prompt", current_question);
if (i === questions.length - 1) {
postman.setNextRequest(null); // No more questions, end the collection runner
} else {
postman.setNextRequest('Prompt');
}
}
Response :
{
"answer": "Adobe is known for its software products, particularly its suite of creative tools such as Photoshop, Illustrator, InDesign, and Premiere Pro. These tools are widely used by professionals in the fields of graphic design, web development, digital media, and video editing. Adobe is also known for its PDF (Portable Document Format) software, which is widely used for document sharing and viewing.",
"question": "what is Adobe?"
}
Iâm trying to send two elements to the form data body key but itâs taking only the 2nd element to the prompt key.
setNextRequest just sets the request that will run after all of the code in the tests tab has been completed.
This means, the âfor loopâ will run to its completion before the next request is run.
Therefore, the last entry in the for loop will always be what is set in the âpromptâ collection variable.
See the following for an example of looping through an array, which utilises a pre-request script to set the current variable, and the tests tab to control the loop.
Simulating 100 users using Pre-Request and Tests -
Help - Postman Community
pre request code :
var array = [
âwhat is RAM?â,
âwhat is adobe?â
];
pm.test(âpre-req array is not emptyâ, () => {
pm.expect(array).to.be.an(âarrayâ).that.is.not.empty;
});
var currentResource = array.shift();
pm.collectionVariables.set(âidâ,currentResource);
pm.collectionVariables.set(âresourcesâ, JSON.stringify(array));
test script :
var array = JSON.parse(pm.collectionVariables.get(âresourcesâ));
var expectedResponse = pm.collectionVariables.get(âidâ);
// If there are elements left in the array, set up the next iteration
if (array.length > 0) {
// Shift the current array element from the array
var currentElement = array.shift();
// Compare the current element with the expectedResponse
pm.test(`Compare element: ${currentElement}`, () => {
pm.expect(currentElement).to.eql(expectedResponse);
});
// Set the current element as the prompt value in the FormData body
pm.request.body.formdata.add({ key: 'prompt', value: currentElement });
// Update the collection variable "resources" with the modified array
pm.collectionVariables.set("resources", JSON.stringify(array));
postman.setNextRequest('Prompt');
} else {
postman.setNextRequest(null);
}
Response:
pre-req array is not empty
FAIL
Compare element: what is adobe? | AssertionError: expected âwhat is adobe?â to deeply equal âwhat is RAM?â
still second element is fetched
I have to add both the elements of array in this prompt in single request.
Can you clarify your request and what you are trying to achieve?
Your last comment mentions that you âhave to add both elements of the arrayâ to the prompt variable and its sent as a single request?
Is that correct? In which case why do you need a loop?
setNextRequest() in an pre-request script will still cause the current request to run. It does not abort the request like you might think. setNextRequest just sets the next request that will run after the current request has run (which includes any code in the pre-request and tests tab).
The âidâ in my example code was specific for that request. Please re-read the example again, and make it relevant to the situation that you are in rather that copy the example verbatim. Take some time to understand the concept. Same goes for the collectionVariable name.
Can you show an example response, and what you currently have in the tests tab please?
This is a working example using Postman Echo.
You need to create a collection variable called prompts with a blank array in the âcurrentâ value. (Square brackets). Otherwise this will fail when it tries to initially parse the array.

Pre-request script
var array = JSON.parse(pm.collectionVariables.get("prompts"));
if (array.length === 0) {
array = [
"What is RAM?",
"What is adobe?"
];
}
pm.test("pre-req array is not empty", () => {
pm.expect(array).to.be.an("array").that.is.not.empty;
});
var currentPrompt = array.shift();
console.log(currentPrompt);
pm.collectionVariables.set("prompt", currentPrompt);
pm.collectionVariables.set("prompts", JSON.stringify(array));
Tests tab
var array = JSON.parse(pm.collectionVariables.get("prompts"));
var expectedResponse = pm.collectionVariables.get("prompt");
var actualResponse = pm.response.json().args.prompt;
pm.test(`tests-tab prompt = ${expectedResponse}`, () => {
pm.expect(actualResponse).to.eql(expectedResponse);
});
if (array.length > 0){
postman.setNextRequest("prompt");
} else {
postman.setNextRequest(null);
}
Console log.

Test run results

Bit caveat is that Iâm still not 100% sure this is what you want. If itâs not, then please clarify what you are trying to achieve.
pre request script :
let array = pm.collectionVariables.get("prompts");
if(!array || array.length == 0) {
array = ["what is Adobe?", "what is RAM?"];
}
let currentprompt = array.shift();
pm.collectionVariables.set("prompt", currentprompt);
console.log(currentprompt)
pm.collectionVariables.set("prompts", array);
test script :
const array = pm.collectionVariables.get("prompts");
const prompts = pm.collectionVariables.get("prompt");
pm.request.body.formdata.add({ key: 'prompt', value: prompts });
if (array && array.length > 0){
postman.setNextRequest("Prompt");
} else {
postman.setNextRequest(null);
}
still getting last element
I want the prompt should be in the formdataâs body
The above image is collection variables
You can put it in the form data. It will read the variable all the same.
What you donât need to do is the following.
pm.request.body.formdata.add({ key: âpromptâ, value: prompts });
You just need to update the collection variable.
You also have slight variances from the working code I provided.
I would recommend using the code I provided as a starter for 10.
Copy the code for the pre-request scripts and tests tab and it should just run.
You can have the body setup as per your screenshot using the form data, and it should still work.
Just make sure you change the prompts array to before you run it.
Also make sure you are running this through the collection runner as setNextRequest() only works with the runner. (You canât just click on send on a request).
Final note is that can you please use the preformatted text option in the editor when pasting code or JSON. Itâs stops everything aligning to the left and making it hard to read.
I used your code but Iâm getting the error. I got the point and I run the collection runner in the console there is this error.
Sorry, its the actual response in the tests tab which you need to update to pull this info from your actual response (instead of Postman Echo that I was using to mimic your response).
I think there is some error in test script in the 4th line:
var actualResponse = pm.response.json().args.prompt;
So, what change should be there? in this line :
var actualResponse = pm.response.json().args.prompt;
Yes, that is correct.
You also need to review the test, as it may not be appropriate in your circumstance.
It was just an example test to check that the response data was the same as the request data sent to Postman Echo.
It uses a concept of string literals to customize the test case name, which is important if you are looping over a lot of data, otherwise you wonât easily be able to tell which request might have failed.
I donât know what you might want to test. So you can probably just remove the test and the expected and actual response variables that go with it and create your own tests.
For this to get both the elements, do I need to run the collection two times.because Iâm getting both elements when I iterate it twice.
I donât know about the rest of the collection as you never mentioned the other requests before now.
To loop though the prompt request, you should not need to run it twice but you need to ensure the prompts array is blank to start with. (That it just shows the two square brackets in the collection variable).
I can only re-iterate the steps that are taking place to control the loop as its important to understand the concept.
Pre request script.
- The pre-request script retrieves the âpromptsâ array.
- If the array is at zero length, then it overwrites the array with a predefined set of elements.
- If your run is successful, you should always be left with a blank array, ready for the next run.
- We have a test in the pre-request script to check that the array exists and is not empty.
- We use the array shift function to retrieve the current prompt. (The first element in the array).
- We then set a collection variable called âpromptâ using the currentPrompt. This will get used in your request, as you have this variable set in your form data.
- We also write back the prompts array (which should now have one less entry).
Tests tab
- We retrieve the prompts array again. (We will need to check the length so we can control the loop)
- In my example script, we also retrieve the current prompt and a value from the response. These are used in an example test, just to ensure what was sent and received are the same.
- You would put a test relevant to your situation here.
- Finally, we have an IF statement that checks the length of the array, and if its higher than zero, it creates a loop by running the same request again using setNextRequest(). Otherwise Postman will run the next request in your collection.
I would recommend creating a new folder, copying the prompt request into it, and then testing it on its own. Run the folder in the collection runner. Hopefully, you will then be able to see the loop working in action and you can then think about integrating it into a larger collection.
1 Like
Just to confirm, you are running this in the âcollection runnerâ?
setNextRequest only works with the runner.
Thanks. Now itâs working
1 Like