DEV Community

reachmmadhu
reachmmadhu

Posted on

Nodejs, How do I wait until the previous post request is completed.

How can i make to wait until I get response from the below snippet before moving with the next line. In Nodejs it is executing further lines of code or functions. Here i am calling GetAccessToken() First and then fn1(). IN this case GetAccessToken is not waiting for the response and get executed fn1() later getting the Token Value. Any help on this would be great.

var log = {
    GetAccessToken: function() 
    {
        var https = require('follow-redirects').https;

        var qs = require('querystring');

        var options = {
        'method': 'POST',
        'hostname': 'corpqa.sts.xxxx.com',
        'path': '/adfs/oauth2/token',
        'headers': {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        'maxRedirects': 20
        };

        var req =  https.request(options, function (res) {
            var chunks = [];

            res.on("data", function (chunk) {
                chunks.push(chunk);   
            });

             res.on("end",  function (chunk) {
                var body = Buffer.concat(chunks);

                console.log(body.toString());        
            });

            res.on("error", function (error) {
                console.error(error);  
            });
            });

        var postData = qs.stringify({
        'grant_type': 'client_credentials',
        'client_id': '0asda7b-a7dc-8582-6b0f-02f6d704d4b0',
        'client_secret': 'm2deXPEvx2sdlRFZtsjkKR_HfDvW5MuDp4',
        'resource': 'urn:webservices:resource:api_webservices:dev',
        'redirect_uri': 'https://xgtwdev.xxxx.com/7777/ssswebsvc/sssdocumentumservicesWeb',        
        'code': '',
        'nonce': 'Nonce Change for each Transaction',
        'state': 'State Change for each Transaction'
        });

        req.write(postData);

        req.end();

    },
    UploadFile:function()
    {
        console.log("Execute UploadFile");
    }
}

module.exports = log
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
saroj990 profile image
saroj sasmal

It would be nice if you could have provided little more context on what you're trying to achieve. From what I understand , I'm assuming that you're trying to execute certain piece of code after you get data from this above code. If that is the case, I would say make this a function and promisify it, and in the calling function you can use then or await on it.

I would do something like this


function httpRequest(req, res) {
 return new Promise((resolve, reject) => {
   https.request(options, function (res) {
    var chunks = [];

    res.on("data", function (chunk) {
      chunks.push(chunk);
    });

    res.on("end", function (chunk) {
      var body = Buffer.concat(chunks);
      console.log(body.toString());
      return resolve(body);
    });

    res.on("error", function (error) {
      console.error(error);
      return reject(error)
    });
  });
 });
}

// some code 
 const result = await httpRequest(req, res);
 // do what you want with the result
// code to be executed after httpRequest 

Enter fullscreen mode Exit fullscreen mode
Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
saroj990 profile image
saroj sasmal

I think there is a couple of issues with the above code. First off https.request is a callback oriented function and assigning a return value from that statement to a variable does not make any sense to me.

Another issue is you are doing something like
req.write() and req.end, I think you should have done that with res object.

Lastly writing the res.write and res.end outside the callback would trigger unpredicted behaviour, this is because by the time request streams data and ends the result, res.write object would have been return the response.

var log = {
  GetAccessToken: function() {
      var https = require('follow-redirects').https;
      var qs = require('querystring');

      var options = {
      'method': 'POST',
      'hostname': 'corpqa.sts.xxxx.com',
      'path': '/adfs/oauth2/token',
      'headers': {
          'Content-Type': 'application/x-www-form-urlencoded'
      },
      'maxRedirects': 20
      };

      https.request(options, function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);   
        });

        res.on("end",  function (chunk) {
          var body = Buffer.concat(chunks);
          console.log(body.toString());
          var postData = qs.stringify({
            'grant_type': 'client_credentials',
            'client_id': '0asda7b-a7dc-8582-6b0f-02f6d704d4b0',
            'client_secret': 'm2deXPEvx2sdlRFZtsjkKR_HfDvW5MuDp4',
            'resource': 'urn:webservices:resource:api_webservices:dev',
            'redirect_uri': 'https://xgtwdev.xxxx.com/7777/ssswebsvc/sssdocumentumservicesWeb',        
            'code': '',
            'nonce': 'Nonce Change for each Transaction',
            'state': 'State Change for each Transaction'
            });
            res.write(postData);
            res.end();   
        });

        res.on("error", function (error) {
          console.error(error);
          // deal with the error, may be you could end the response here
        });
      });
  },
  UploadFile:function()
  {
      console.log("Execute UploadFile");
  }
}

module.exports = log

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
reachmmadhu profile image
reachmmadhu

Thanks for your response. I tried and it din't work. Apologize if my code is confusing. Let me share a simplified version

Collapse
 
saroj990 profile image
saroj sasmal • Edited

How do you call the functions ? it would be great if you can post that code too and what is fn1(), you haven't explained what does it do ? If you post the code, that would help anyone who is looking at the code, understand the code pretty quickly.

PS: you should remove the client secret and key from the code. It's not a good idea to share those thing with code. Just a suggestion!

Thread Thread
 
reachmmadhu profile image
reachmmadhu • Edited

Thanks for your response and helping me on this. Apologize for all the confusion. Below is the simplified version of the same code which i have shared.

var data ="xxxx"
let XMLHttpRequest1 = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest1();
xhr.withCredentials = true;
xhr.open("POST", "https://corpqa.sts.xxxx.com/adfs/oauth2/token");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
console.log("Execution Order 1");
xhr.addEventListener("readystatechange",  function() {
  if(this.readyState === 4) {
    console.log("Execution Order 2");
    //console.log(this.responseText);

  }
});
console.log("Execution Order 3");
Enter fullscreen mode Exit fullscreen mode

Issue: How do i make code to WAIT for response and execute this.readyState ===4. before it proceed to execute console.log("Execution Order 3").
Currently, below is the output:

Execution Order 1
Execution Order 3
Execution Order 2
Enter fullscreen mode Exit fullscreen mode

Could you please help me getting the output in below order:

Execution Order 1     
Execution Order 2
Execution Order 3
Enter fullscreen mode Exit fullscreen mode

Any help on this would be great!

Thread Thread
 
saroj990 profile image
saroj sasmal • Edited

There are two ways you can achieve this

  1. putting the last console log inside the callback of addEventlistener, it means your console log would be inside the addEventlinstener but after the if statement

  2. make the code that uses callback addEventListene a separate async method, simply use await on that method.