从请求 npm 获取数据
Get data from request npm
我正在使用 express js 构建一个应用程序并使用请求 (v-2.88.2) 从 api
获取数据
request(url, function(error, request, body) {
var data = JSON.parse(body);
});
我想在其他函数中使用var数据。
有没有办法做到这一点?
如果您想在其他函数中使用 data
,只需在该函数中作为参数传递即可,即
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)
});
}
当然,如果你做不到就很难做。
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);
});
您好,您可以通过将变量设置为全局变量来做到这一点。这不是很好的方法,但我们可以做到这一点
var data;
request(url, function(error, request, body) {
data = JSON.parse(body);
});
这样,您甚至可以在函数之外访问数据变量。希望这对你有帮助。
我正在使用 express js 构建一个应用程序并使用请求 (v-2.88.2) 从 api
获取数据request(url, function(error, request, body) {
var data = JSON.parse(body);
});
我想在其他函数中使用var数据。
有没有办法做到这一点?
如果您想在其他函数中使用 data
,只需在该函数中作为参数传递即可,即
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)
});
}
当然,如果你做不到就很难做。
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);
});
您好,您可以通过将变量设置为全局变量来做到这一点。这不是很好的方法,但我们可以做到这一点
var data;
request(url, function(error, request, body) {
data = JSON.parse(body);
});
这样,您甚至可以在函数之外访问数据变量。希望这对你有帮助。