简体   繁体   中英

How to make response data available outside the function

Data received from the server is written into variable cols . But it is empty in the output. I'm not sure if cols has now a proper value and is available to work with.

    app.post('/get_columns', function (req, res, next) {
          var cols = '';
          var httpreq = http.request(options, function (response) {
            response.on('data', function (chunk) {
              cols += chunk;
              console.log("body: " + cols);
            });
          });
          httpreq.write(options_data);
          httpreq.end();
          console.log('cols: '+cols);
      });

What output shows:

cols: 
body: {"ResultSet Output":[{"NAME": "PART_COL1"},{"NAME": "PART_COL2"}],"StatusCode": 200,"StatusDescription": "Execution Successful"}

HTTP Calls are asynchronous call in Node.js and the response comes as multiple chunks through Events . When you are dealing with HTTP request in Node.js, you have to deal with "data" & "end" events on the response object given by HTTP.

Below examples shows how you can deal with the response in HTTP:

app.post('/get_columns', function (req, res, next) {
  var cols = '';
  var httpreq = http.request(options, function (response) {
    // This event is triggered multiple times whenever a chunk is available.
    response.on('data', function (chunk) {
      cols += chunk;
    });

    // This event is triggered once when all the chunks are completed.
    response.on('end', function (chunk) {
      console.log("body: " + cols);
    });
  });
  httpreq.write(options_data);
  httpreq.end();
});

Another organized way to handle

var fetchCols = function (options, options_data) {
  return new Promise((resolve, reject) => {
    var cols = '';
    var httpreq = http.request(options, function (response) {
      // This event is triggered multiple times whenever a chunk is available.
      response.on('data', (chunk) => {
        cols += chunk;
      });

      // This event is triggered once when all the chunks are completed.
      response.on('end', () => {
        resolve(cols);
      });
    });

    // This event is triggered when there is any error.
    httpreq.on('error', (e) => {
      reject(e);
    });
    httpreq.write(options_data);
    httpreq.end();
  });
};

app.post('/get_columns', function (req, res, next) {
  fetchCols(options, options_data)
    .then((cols) => {
      console.log('body: ', cols);
    })
    .catch((err) => {
      console.error('ERR: ', cols);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM