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;
答案 0 :(得分:0)
getStaticRoomList
不会返回任何内容,因为回调函数内的代码在函数终止后很久就会执行。您还应该为getStaticRoomList
定义另一个回调函数。
所以最后,要获得数组,你会做类似
的事情var StaticRoomList;
Initializer.getStaticRoomList(fs, DOMParser,function(result){
StaticRoomList = result;
});
在getStaticRoomList
内的回调中,您只需调用getStaticRoomList
答案 1 :(得分:0)
JS中的函数是异步的。
您必须将回调函数作为参数传递。
下面是一个例子:
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
}
})