Get data from request npm

1.1k views Asked by At

I'm building an app using express js and using request(v-2.88.2) to get data from an api

request(url, function(error, request, body) {
    var data = JSON.parse(body);
});

I want to use var data in other functions.

Are there any ways to do this?

3

There are 3 answers

0
CodeBug On BEST ANSWER

hi you can do this by making you variable as global. its not really good method but we can do this

var data; 
request(url, function(error, request, body) {
data = JSON.parse(body);
});

by this, you can even access your data variable outside of your function too. hope this may help you.

2
Himanshu Pandey On

If you want to use data in other functions just pass as arguments in that functions i.e.

request(url, function(error, request, body) {
    var data = JSON.parse(body);
    // call another function and pass as arguments
    antoherFunctions(data);

});


function anotherFunctions(data){
  // use data as per requirement 
  request(data.url, function(error, request, body) {
    var anotherData = JSON.parse(body);
    console.log(anotherData)
  });
}
2
Chase On

Sure, it would be hard to do much if you couldn't.

function doStuffWithData(theData) {
  // This is your other function

  // E.g. make another dependent request
  const secondRequestUrl = theData.url;
  request(secondRequestUrl, function(error, request, body) {
    var evenMoreData = JSON.parse(body);
    // Do even more stuff with your second request's results
  });
}

request(url, function(error, request, body) {
  var data = JSON.parse(body);

  // Use data in another function:
  doStuffWithData(data);
});