0

Total postman noob. I have a script (well I don't I am trying to) to do the drudge tasks of authentication and authorization which takes 2 requests:

console.log("START");
var authenticationToken;
// Identity token
var authenticationTokenRequest = {
  url: 'xxxx',
  method: 'POST',
  timeout: 0,
  header: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic xxxxx="
  },
  body: {
    mode: 'urlencoded',
    urlencoded: [
        {key: "grant_type", value: "password"},
        {key:"username", value: "xxxxx"},
         {key:"password", value: "xxxx"},
    ]}
};

pm.sendRequest(authenticationTokenRequest, function (err, res) {
    **console.log("01 send first request body");**

    var responseJson = res.json();
    console.log(responseJson);
    pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);
    authenticationToken = responseJson['access_token'];
});
**console.log("Authentication token local var: " + authenticationToken);
console.log("Authorization token env var: " + pm.environment.get('ACCESS_TOKEN'));**
var authorizationTokenRequest = {
    url: "xxxx",
    method: "POST",
    header: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + authenticationToken,
        "Accept": "application/xxx+json"
    },
    body:{
        tenantId: "xxx",
        deviceId: "xxx"
    }
}

pm.sendRequest(authorizationTokenRequest, function (err, res) {
    **console.log("02 second request call");**
    var responseJson = res.json();
    pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);

});
//

When I run this and look at the console, the console messages of the local vars show undefined. The console message for the second request shows in console before the first request. The second request depends on a value from the first.

What am I doing wrong? Thanks

user2919960
  • 71
  • 11
  • 1
    The only thing you're doing wrong is failing to understand the asynchronous nature of network requests. Your second `pm.sendRequest` is configured to start _before_ the first `pm.sendRequest` even has a chance to get started! If you want to something to happen _after_ a request completes, it needs to happen _inside_ the completion function curly braces, not _after_ the closure of the `sendRequest` parentheses. – matt Oct 31 '22 at 13:12
  • Well damn. Because of course it does. I feel like I need a 2x4 smacked up my head. – user2919960 Oct 31 '22 at 13:14
  • See https://community.postman.com/t/async-operations/24314/3. As that thread shows, there _has_ been an attempt to simulate `async/await`, which would allow you just to take things in series order; but I would avoid that if I were you, as it is not at all _true_ `async/await`, it's just a hack. Use the nested format shown in the first code of the linked post. – matt Oct 31 '22 at 13:17

0 Answers0