0

i'm tryna get my array of results out of the callback method, the array is containing all of those things i want in but i can use it outside of the functions always keep undefined result. I was looking on many website for helping me to improve it but no results.

var DOMParser = require('xmldom').DOMParser;
var fs = require('fs');
var Initializer = require('./Initializer');
var StaticRoomList = Initializer.getStaticRoomList(fs, DOMParser);
console.log(StaticRoomList);

openRoomListXML = function(fs, DOMParser, callback){
try{
    fs.readFile('./XML/RoomList.xml', function(e, data){
        if(e){
            callback(e);
        }
        else{
            var BuffertoXMLString = String(data);
            var XMLOutput = new DOMParser().parseFromString(BuffertoXMLString, "text/xml");
            var XMLDocument = XMLOutput.documentElement;
            callback(null, XMLDocument);
        }

    });

}
catch(fsException){
    console.log(fsException);
}
};

getStaticRoomList = function(fs, DOMParser){
openRoomListXML(fs, DOMParser, function readList(e, XMLDocument){
    if(e){
        console.log(e);
    }
    else{
        var nodeList = XMLDocument.getElementsByTagName("room");
        var arrayRoomList = [];
        for(i = 0; i < nodeList.length; i++){
            arrayRoomList.push(nodeList[i].childNodes[0].nodeValue);
        }
        return arrayRoomList;
    }
});
};


 exports.getStaticRoomList = getStaticRoomList;
Aupedeus
  • 3
  • 4

2 Answers2

0

getStaticRoomList doesn't return anything since the code inside the callback function is executed long after the function is terminated. You should define another callback function for getStaticRoomListtoo.

So in the end, to obtain the array you will do something like

var StaticRoomList;
Initializer.getStaticRoomList(fs, DOMParser,function(result){
   StaticRoomList = result;
});

And in the callback inside getStaticRoomList, instead of trying to return the result, you simply call the callback function of getStaticRoomList

0

Functions in JS are async.

You have to pass a callback function as a parameter.

Below there is an example:

    getStaticRoomList = function(fs, DOMParser, callBack){
openRoomListXML(fs, DOMParser, function readList(e, XMLDocument){
    if(e){
        console.log(e);
    }
    else{
        var nodeList = XMLDocument.getElementsByTagName("room");
        var arrayRoomList = [];
        for(i = 0; i < nodeList.length; i++){
            arrayRoomList.push(nodeList[i].childNodes[0].nodeValue);
        }
        callBack(arrayRoomList);
    }
});

getStaticRoomList(fs, DOMParser, function(error, result){
    if(error != null){
        //Deal with resul
    }
})
Rodrigo Morbach
  • 378
  • 4
  • 16