2017-04-11 24 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