Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

node.js - Create an async function for Https NodeJs request, thus, waiting for the async response to return a value

I'm trying to create an https request, with native NodeJs, that is able to return the response value when this latter is returned by the https request.

The problem is that, if I don't make the function async, the code return the value (in the following example code the value is the "Hello" string), concluding the script, before the https response is given.

Here my code:

exports = function(){
  
  var https = require('https');
  var fs = require('fs');
  
  var qs = require('querystring');
  
  var options = {
    'method': 'POST',
    'hostname': '***.it',
    'path': '***',
    'headers': {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    'maxRedirects': 20
  };
  
  async function doSomethingUseful() {
    // return the response
    return await req;
  }

  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: " + body.toString());
      var b = JSON.parse(body);
      var access_token = b.access_token;
      
      
    });
  
    res.on("error", function (error) {
      console.error(error);
    });
  });
  
  var postData = qs.stringify({
    'client_id': '***',
    'client_secret': '***',
    'grant_type': '***'
  });
  
  req.write(postData);
  
  req.end();
                
  return "Hello";
};

What I need is to return the "access_token" variable inside the "res.on", but I don't know how to do that.

Thank you very much in advance!

question from:https://stackoverflow.com/questions/65844002/create-an-async-function-for-https-nodejs-request-thus-waiting-for-the-async-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...