Populating array of arrays from inside a pm.sendRequest

Hi, I am trying to understand how pm.sendRequest works.

I have a query and some Tests code that loops through a response and makes a second request using pm.sendRequest with variables from the initial response.

This works, but within the pm.sendRequest I have a loop that creates an array that I need to push into a global array (defined before pm.sendRequest is called).

The problem is the pushing doesn’t work. I end up with an empty array.

So my question is: are variables that are supposed to be global (to the code, not Postman global variables) not available inside pm.sendRequest?

Code sample:


let myArray = [];

pm.sendRequest( url, function (err, response){

      let foo = [];   
      //a for loop here that push populates foo[] just fine
      for {
          foo.push(name);
      } //end loop

      console.info(foo); //all good

myArray.push(foo);
 });

console.info(myArray); //empty

foo array is properly populated at the end, but my Array is empty.

Any ideas?

Thanks.

I THINK if you just define foo outside the pm.sendRequest (right after let myArray = ) you will be able to see it within and outside of it.

Yes, I see it, the problem was the timing.

By the time console.info was printing the value of myArray, the sendRequest wasn’t finished yet, due to its async nature, which I learned about after posting the question.

There are ways to do async operations of this nature in Postman, but the true answer is in not using this approach, and using the collection runner instead.