为什么我不能在请求函数中访问JSON属性?

时间:2019-07-25 17:21:45

标签: javascript node.js json api

我正在尝试访问JSON对象,因此我可以映射数据并对其进行操作。但是,我似乎无法在请求功能之外访问它。我将请求函数放在变量中,并试图通过调用父级的属性来调用它,但是在命令行中我读到“ undefined”,这是我做错了什么?

1)我尝试在请求函数中使用push()方法,因此我可以创建一些原型对象来存储所有数据,然后将其包含在函数中,以便可以在请求外使用它,但是我得到了错误“ .push()不是函数”

   var r = request(options, function (error, response, xyz) {
        var deviceData = JSON.parse(xyz);

        if (error) throw new Error(error);

        for (var i = 0; deviceData.data.length > i; i++) {
            var extractedData = [];
            extractedData = deviceData.data[i];

        };
           //this executes an entire JSON object with all the data I need
          //console.log(extractedData);      
});
//my console shows "undefined"
console.log(r.extractedData);

我希望像在console.log中的请求函数中那样获得一个完整的JSON对象。相反,我得到“未定义”

已更新 我尝试按照@ajaykumar的建议使用诺言,遇到了上述问题

var xyz = {};
var r = {};
Getdata().then(data => {
    r["extractedData"] = data;
    //console shows all the data as inside the promise block
    //console.log(data)
}, err => console.log(err)); 

 function Getdata() {
     return new Promise((resolve, reject) => {
         request(options, function (error, response) {
             var deviceData = JSON.parse(response.body);
             //console.log(xyz) at this point shows all data, message: call successful" and the data looks like this:
[console.log(xyz)][1]
//response shows the entire object too, but it is through Node.js, so you actually see my object contained by the "body" property of Node.js. I didn't think about this before. So now I modified my code and removed xyz as it is actually not necessary

             if (error) reject(error);


             var extractedData = [];
             for (var i = 0; deviceData.data.length > i; i++) {
                 extractedData.push(deviceData.data[i]);
             };
             //the console shows all my data
             //console.log(extractedData)
             resolve(extractedData);
         });
         //the console no longer associates extractedData, displays "extractedData is undefined"
         //console.log(extractedData)
     });
}
//console prompts error "ReferenceError: data is  not defined", if I try extractedData instead it gives me the same old message "undefined". If I try r[0] I get "undefined"
//console.log(data);

1 个答案:

答案 0 :(得分:-2)

由于请求将以异步方式执行,因此它不会等待请求完成,因此它将在我们从请求获得响应之前执行下一行,因此未定义。

Var r = {}
request(options, function (error, response, xyz) { 
var deviceData = JSON.parse(xyz); 
if (error) throw new Error(error); 
for (var i = 0; deviceData.data.length > i; i++) { var extractedData = []; extractedData = deviceData.data[i]; };

 r["extractedData"] = extractedData;

   console.log(extractedData);
 }); 

// this will execute before request gets complete hence it is undefined
 console.log(r.extractedData);

因此创造诺言

Getdata() {
return new promise ((resolve, reject) =>{
   request(options, function (error, response, xyz) { 
    var deviceData = JSON.parse(xyz); 
    if (error) reject (error) ;
    var extractedData = []; 
    for (var i = 0; deviceData.data.length > i; i++)
{ 
 extractedData.push(deviceData.data[i]);
 };   
       resolve (extractedData) 
     }); 
}
}

调用此功能

Var r ={}
Getdata ().then(data=>{
 r["extractedData"] = data;
},err=>console.log(err)) 

这将解决您的问题