0

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) //all good
 });

console.info(myArray); //empty

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

Any ideas?

Thanks.

1 Answers1

0

After much searching on this, I found that the pm.sendRequest method is an asynchronous request: https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#sending-requests-from-scripts:~:text=You%20can%20use%20the%20pm.sendRequest%20method%20to%20send%20a%20request%20asynchronously%20from%20a%20Pre%2Drequest%20or%20Test%20script.

That means it's not a blocking request and it runs in the background, independently of the code that follows it.

As such, the last console.log. output does not wait for the pm.sendRequest function to complete and populate the array.

Some workarounds for this are possible, using global variables and promises:

https://community.postman.com/t/can-i-use-pm-sendrequest-to-send-requests-synchronously/225/14

https://james.jacobson.app/javascript-promises-and-postmans-sendrequest/

https://stackoverflow.com/a/53934401/10792097

However, overall, it looks like this is not the way to go about it in the Postman universe.

I think we're supposed to split out each request by itself and use request workflows: https://learning.postman.com/docs/running-collections/building-workflows/

This is what I'll be trying to do next.