I'm trying to parse a XML file, build a object of that infos and push the results to an array. This runs on a node js server so I use promises to do this synchron. In the parseImportantInfos
method all parsed objects are printed correct to the console, but after I resolve this objects to the getLocations
methode and console.log again only the first situationrecord of one situation will be resolved.
The XML looks like:
...
<situation>
<situationrecord version="123">...</situationrecord>
<situationrecord version="123">...</situationrecord>
</situation>
<situation>
<situationrecord version="456">...</situationrecord>
<situationrecord version="456">...</situationrecord>
</situation>
...
<!-- sometimes there is only one situationrecord -->
<situation>
<situationrecord version="789">...</situationrecord>
</situation>
This is the part of my code where the parsed objects get "lost".
let getLocations = function(xmlArr) {
return new Promise(function(resolve, reject) {
for (var x in xmlArr) {
var $ = cheerio.load(xmlArr[x]);
var promiseList = [];
$('situation').each(function() {
var newPromise = parseImportantInfos($, this)
.then(function(obj) {
console.log(obj); // <---- Here are parsed situations missing, only the first situationrecord of a situation is received
if (obj != "") {
constructionsites.push(obj);
}
});
promiseList.push(newPromise);
});
Promise.all(promiseList)
.then(function() {
resolve(constructionsites);
});
}
});
};
let parseImportantInfos = function($, record) {
return new Promise(function(resolve, reject) {
$(record).find('situationRecord').each(function() {
var startLocationCode = $(this).find('alertCMethod2SecondaryPointLocation').find('specificLocation').text();
var endLocationCode = $(this).find('alertCMethod2PrimaryPointLocation').find('specificLocation').text();
var managementType = $(this).find('roadOrCarriagewayOrLaneManagementType').text();
if (startLocationCode != '' && endLocationCode != '' && managementType != 'roadClosed') {
createSituationRecord($, this, startLocationCode, endLocationCode)
.then(function(obj) {
console.log(obj); // <----------- This log prints all parsed infos correct
resolve(obj);
})
.catch((err) => {
reject("There was an error while parsing the xml");
console.log('err', err.stack);
});
} else {
resolve("");
}
});
});
};
I already debugged the project but can't figure out why only one part of the object where resolved