在我的应用程序的后端内部有一个函数,目的是返回与特定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
})
不是一个范围的问题,它异步回调的问题,有很多的职位,以检查的 – juvian
可能的复制[为什么是我的变量不变后,我修改函数里面? - 异步代码引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Andreas
在这里,它还不足以确保'forEach'完成 - 您还必须确保每个'findOne'调用都完成。您可能需要[async](https://caolan.github.io/async/)库。 – MultiplyByZer0