Can I reuse a JavaScript variable across requests?

Is there any way to preserve my Javascript environment across requests in a collection run? I need to use javascript to extract an ID in one request, and then use that ID in the next request in the run.
I can do that using environment variables, and thatā€™s fine.

However, what I next want to do is to push the ID numbers onto an array, and then pop them off in a later request. That means preserving the array across requests.

Is there any way to do that in JavaScript? The only way I can see is to serialize the array into a string, store it into an environment variable, and then deserialize it in a later request.

Any ideas?

Hey there, welcome to the community!

I think I get the gist of your question but a few more clarifying details would be helpful. Hereā€™s some best practices around getting the answers you need.

Using the environment variables is how Iā€™d recommend doing that. Can you clarify what you mean by ā€œpop them off in a later requestā€ ? Not sure what pop off means :slight_smile:

1 Like

Hey @TeacherManAlex,

Your idea is correct, the pattern I typically put in place for this type of operation is:

const myArray = pm.environment.has('myArray') ? JSON.parse(pm.environment.get('myArray') : [];

const responseData = pm.response.json();
myArray.push(responseData.myValue);

pm.environment.set('myArray', JSON.stringify(myArray));

Then in the consuming request, I would do exactly as you suggested:

const myArray = JSON.parse(pm.environment.get('myArray'));
const myVariable = myArray.pop();

// Do work with the variable

pm.environment.set('myArray', JSON.stringify(myArray));

@hannah.neil, ā€˜popā€™ refers to taking the last item from an array :slight_smile:

2 Likes

Ah, that makes sense. Adding that to my vocabulary. Thanks for chiming in!

2 Likes