0

I have a problem with variable re-using inside pre-request in postman. enter image description here

In pre-request I try run request 1 and request 2

Request 2 uses variable from request 1 response

The problem is that "guid" variable keeps old value until pre-request will be not completed

pm.sendRequest({
    url: pm.environment.get("request_1"),
    method: 'POST',
    header: {
        'Content-Type': 'application/json'
    }

}, function (err, res) {
    console.log(res.json());
    pm.environment.set("uuid", res.json().uuid)
    pm.environment.set("date_1", res.json().data.object.date_1);
    pm.environment.set("date_2", res.json().data.object.date_2);
    pm.environment.set("guid", res.json().data.object.guid)
});
pm.sendRequest({
    url: pm.environment.get("request_2/") + guid,
    method: 'POST',
    header: {
        'Content-Type': 'application/json'
    }

}, function ()
);
  • 1
    Can't fully understand the question, pls rewrite the description, add code or steps to reproduces the problem. – lucas-nguyen-17 Oct 13 '22 at 11:14
  • @lucas-nguyen-17 hi, I've updated description, the problem - I need to receive new value of "guid" variable while pre request is running, not completed. However it keeps old value until pre-request will be not completed – Artur Tsoy Oct 17 '22 at 10:35
  • the problem is `pm.sendRequest` is async, it does't guarantee that `request_1` finishes before `request_2`. – lucas-nguyen-17 Oct 17 '22 at 10:47
  • ooo, I got you, is there any way to solve this problem?? or maybe a direction where should I dive into? – Artur Tsoy Oct 18 '22 at 06:26
  • I haven't investigated this kind of problem, but I found this, hope it will help you out. https://stackoverflow.com/a/73989869/7574461 – lucas-nguyen-17 Oct 18 '22 at 06:47

1 Answers1

0

It works for me:

pm.sendRequest({
   url: pm.environment.get("request_1"),
   method: 'POST',
   header: {
      'Content-Type': 'application/json'
   }
 }, function(err, res) {
   console.log(res.json());
   var guid = res.json().data.object.guid;
   pm.environment.set("uuid", res.json().uuid)
   pm.environment.set("date_1", res.json().data.object.date_1);
   pm.environment.set("date_2", res.json().data.object.date_2);
   pm.environment.set("guid", guid);

   pm.sendRequest({
      url: pm.environment.get("request_2/") + guid,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      }
   }, function());
});

Explanation:

There are two issues with your code: 1 - Postman does not respect the order of the requests, so you need to ensure this order programmatically by nesting the functions. 2 - The variable "guid" is being set in the environment, but you are trying to access it locally. You can declare it or access it by using pm.environment.get("guid").