I'm trying to fill an array of numbers after a http get request. I implemented a function that should return this array, but when I try to use it, it is empty. I tried to console.log the array inside the function and it is correctly filled with what I expected, but it appears to log after the execution of the function instead of during execution.
I don't understand how to wait until the function fills the array to use it properly, can you help me? Is it ok to use .then methods inside other .then?
Here is the code, that I simplified a bit to make it more understandable:
router.get('/newRail/:trainNumber', function (req, res) {
railsAvailable(req.params.trainNumber).then(function (placing) {
res.json(placing);
// If you read placing at this moment it results empty
});
});
function railsAvailable(trainNumber) {
return Promise.resolve(findBadRail(trainNumber));
}
function findBadRail(trainNumber) {
var badRail = [];
getPlacingByTN(trainNumber).then(placing => {
badRail.push(placing.rail);
getAllPlacings().then(allPlacings => {
allPlacings.forEach(function (p) {
//some computation on the array here...
// .....
// .....
badRail.push(p.rail);
});
console.log(badRail)
});
});
return badRail;
}
function getPlacingByTN(trainNumber) {
// getting from a mongoDb collection
return CollectionDB.findOne({"trainNumberArr": {$eq: trainNumber}}, {});
}
function getAllPlacings() {
// getting from a mongoDb collection
return CollectionDB.find();
}