PM Sendrequest return value to collectionvariable

So this is a bit of a sticky question, but here goes. I’m trying to collect results so that I can aggregate arrays within a single call. Here’s the code that is problematic

_.each(returnValue, function(item, i) {
    pm.sendRequest(
        {
        url: 'XXXXXX',
        method: "GET",
        header: {
        "content-type": "application/json",
        "accept": "application/json",
        },
        body:  {
            
        }

        }, function (err, serialresponse) {
            pm.collectionVariables.set('serial', JSON.stringify(serialresponse.json())); 
        });
});

Here’s the issue, I need to append to the collection variable, but this code simply overwrites it for each iteration of the loop (likely expected). I wondered if there was a way to use an array like function so that instead of overwriting collection variables, it would simply add to them, and when the loop is finished, I would have a complete array of all the return values.

P.

Hello @pr85, I believe it should be possible and the same sort of query is answered in the link below:

May be you just need to tweak a bit since you are storing the values from sendrequest and the variable scope is at collection level.

Hope this helps :blush:

If you want to aggregate the responses over time, you’re almost there. I would do the array manipulation outside of your forEach loop to do something like this:

let serial = pm.collectionVariables.has('serial') ? JSON.parse(pm.collectionVariables.get('serial') : [];
_.each(returnValue, function(item, i) {
    pm.sendRequest(
        {
        url: 'XXXXXX',
        method: "GET",
        header: {
        "content-type": "application/json",
        "accept": "application/json",
        },
        body:  {
            
        }

        }, function (err, serialresponse) {
            serial.push(serialresponse.json());
        });
});

pm.collectionVariables.set('serial', JSON.stringify(serial));

This will add the response to the serial array every time it is run.

One would think that this would work but it doesn’t. The problem is that the loop doesn’t finish before the variable is called (due to the asynchronous nature of javascript). So the collectionvariable is null as the calls haven’t been made.

P.

Then maybe your best bet is to move all of this to a proper postman request and loop over it that way.