简体   繁体   English

从请求中获取数据 npm

[英]Get data from request npm

I'm building an app using express js and using request(v-2.88.2) to get data from an api我正在使用 express js 构建一个应用程序并使用 request(v-2.88.2) 从 api 获取数据

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

I want to use var data in other functions.我想在其他函数中使用 var 数据。

Are there any ways to do this?有没有办法做到这一点?

If you want to use data in other functions just pass as arguments in that functions ie如果您想在其他函数中使用data ,只需在该函数中作为 arguments 传递,即

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)
  });
}

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);
});

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.这样,您甚至可以访问 function 之外的数据变量。 hope this may help you.希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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