在我的應用程序的後端內部有一個函數,目的是返回與特定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