Home > Net >  Undersanding request get in node.js
Undersanding request get in node.js

Time:09-28

I'm trying to do a GET request in node.js. I would like to access the result of the request but there is a problem. Here is the code :

const https = require('https');
var data;

https.get('https://www.example.com', (resp) => {

  resp.on('data', (chunk) => {
    data  = chunk;
  });

  resp.on('end', () => {
    console.log("Inside : " data "\n"); 
  });

}).on("error", (err) => {
  console.log("Error: "   err.message);
});

console.log("Outside : " data "\n"); 

The outside message appears before the inside one, and only the latter displays the request. That is due to asynchronous process I guess. But if I want to use my request outside, it's a problem because of this delay. How may I do?

CodePudding user response:

Your code execute asyncronymos. http.get(...) execute, but programm don't wait result of your get. So when you do "console.log("Outside : " data "\n");" - your data is empty. You will never get data to outside message, without js constructions like async/await.

CodePudding user response:

Thanks for answering. After searches, I made this, which work, but I don't know if it's the best way to do this.

const https = require('https');
var data;

(async function () {

  var p = new Promise((resolve) => {https.get('https://www.example.com', (resp) => {

      resp.on('data', (chunk) => {
        data  = chunk;
      });

      resp.on('end', () => {
      console.log("\n\n===>Inside : " data "\n");
      resolve();

      });

    }).on("error", (err) => {
      console.log("Error: "   err.message);
    });
    
  });

  await p;
  console.log("\n\n===>Outside : " data "\n"); 
})();

CodePudding user response:

This is what you need:

(async function () {
  const https = require('https');
  var data;

  await new Promise((resolve, reject) => {https.get('https://www.example.com', (resp) => {

      resp.on('data', (chunk) => {
        data  = chunk;
      });

      resp.on('end', () => {
      console.log("\n\n===>Inside : " data "\n");
      resolve();

      });

    }).on("error", (err) => {
      console.log("Error: "   err.message);
      reject();
    });
    
  });

  console.log("\n\n===>Outside : " data "\n"); 
})();
  • Related