2017-04-11 26 views
2

在我的应用程序的后端内部有一个函数,目的是返回与特定thingID相关的所有传感器。在Javascript中使用对象数组的范围问题

我被填充新的阵列allSensors接近这一点,但是当记录下面

console.log(allSensors); 
res.send(allSensors) 

它是一个空数组[]

我还应该注意到,传感器的各个元件正确记录

我已将

console.log(allSensors) 

进入sensor.findOne循环,并打印出正确的元素。

existingThing.sensors.forEach(function (element) { 
      Sensor.findOne({_id: element._id}, function (err, sensor) {    
       if(sensor){ 
        // console.log(sensor); 
        allSensors.push(sensor); 
        console.log(allSensors); // this works.... 
       }  
      })    
     }); 

有关此行为的任何想法? 感谢

//get all sensors associated with thingid 
app.get('/api/things/:thingid/sensor', function (req, res) { 
    var allSensors = []; 
    Thing.findOne({ 
     thingID: req.params.thingid 
    }, function (err, existingThing) { 
     if (!existingThing) 
      return res.status(409).send({ 
       message: 'Thing doesnt exist' 
      }); 
     if (existingThing.sensors.length < 0) 
      return res.status(409).send({ 
       message: 'No sensors' 
      });  
     existingThing.sensors.forEach(function (element) { 
      Sensor.findOne({_id: element._id}, function (err, sensor) {    
       if(sensor){ 
        // console.log(sensor); 
        allSensors.push(sensor); 
       }  
      })    
     }); 
    }) 
    console.log(allSensors); //empty 
    res.send(allSensors); //empty 
}) 
+0

不是一个范围的问题,它异步回调的问题,有很多的职位,以检查的 – juvian

+2

可能的复制[为什么是我的变量不变后,我修改函数里面? - 异步代码引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Andreas

+0

在这里,它还不足以确保'forEach'完成 - 您还必须确保每个'findOne'调用都完成。您可能需要[async](https://caolan.github.io/async/)库。 – MultiplyByZer0

回答

0

安装async库。 (这是一个非常有用的库,如果你不使用它,你可能不得不重新创建它)。然后用这个代码:

async.each(existingThing.sensors, function(element, _cb) { 
    Sensor.findOne({ _id: element._id }, function(err, sensor) {    
     if(sensor) { 
      allSensors.push(sensor); 
     } _cb(); 
    }); 
}, function() { 
    console.log(allSensors); 
    res.send(allSensors); 
}); 
+0

非常感谢你,相当新的JS,所以不断失踪这样的小事情。 – LukeAS

+0

@LukeAS谢谢。我的答案是否有效? – MultiplyByZer0

+0

确实如此,欢呼声 – LukeAS