1

I am trying to store the response of an http request made using nodejs by request module but the problem is I can't acsess it after the request is completed in more details we can say after the callback

How I can add it

Here is what I tried till now

Tried to use var instead of let Tried passing it to a function so that i can use it later but no luck

Here is my code can anyone help actually new to nodejs that's why maybe a noob question

var request = require('request')
var response

  function sort(body) {
    for (var i = 0; i < body.length; i++) {
      body[i] = body[i].replace("\r", "");
    }
      response = body
      return response
  }

  request.get(
    "https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all",
    (err, res, body) => {
      if (err) {
        return console.log(err);
      }
      body = body.split("\n");
      sort(body);
    }
  );

console.log(response)

In this I am fetching up the proxies from this api and trying to store them in a variable called as response

1 Answers1

0
var request = require("request");
var response;

async function sort(body) {
  await body.split("\n");
  response = await body;
  console.log(response); // this console log show you after function process is done. 
  return response;
}

request.get(
  "https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all",
  (err, res, body) => {
    if (err) {
      return console.log(err);
    }

    sort(body);
  }
);

// console.log(response); //This console log runs before the function still on process, so that's why it gives you undefined.
  • Try this code it works fine I just tested.
  • put the console log inside the function so you can see the result.
  • The console.log that you put actually runs before you process the data so that's why you are getting "undefined".
  • Actually, you will get the data after the sort Function is done processing.
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Enis Gur
  • 89
  • 1
  • 9