0

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?

Deepak singh
  • 35
  • 1
  • 4
  • There are various ways. You could for example store it globally, though I would prefer passing it to the functions which need the data – max May 30 '20 at 19:31
  • @zirmax I want to use it another request so i can't simply just pass it in a function. – Deepak singh May 30 '20 at 19:38
  • It really depends, but you should make it accessible in the parent scope. Use a piece of state in your frontend framework. Create a variable in the parent scope. Use redux and dispatch an appropriate action. Store it in localStorage and read it elsewhere. Use a cookie. Just make it accessible in another scope. – Malik Brahimi May 30 '20 at 20:02
  • Also this package is deprecated. – Malik Brahimi May 30 '20 at 20:02

3 Answers3

1

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)
  });
}
Himanshu Pandey
  • 688
  • 2
  • 8
  • 15
1

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.

CodeBug
  • 1,649
  • 1
  • 8
  • 23
0

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);
});
Chase
  • 3,028
  • 14
  • 15
  • I want to use it another request so i can't simply just pass it in a function. – Deepak singh May 30 '20 at 19:39
  • You can make your other request either in that location or inside your function that you are passing it to as an argument. Nothing stops that. – Chase May 30 '20 at 19:41