Anthony Anthony - 3 months ago 9
Javascript Question

Function return nothing

I build this function but it return nothing :

function myFunction(index){
var resultat = "";
fs.readFile(__dirname + '/File.xml', function(err, data) {
parser.parseString(data, function (err, result) {
resultat = result['level1']['level2']['level3'][index];
//console.log(resultat); // works
});
});
return resultat;// Return nothing
// return 'test' // Works
}


Hope you will can help me !

Answer

Your function returns before your xml call has time to load the remote XML.

Try:

function getItem(index, callback){
    var resultat = "";
    fs.readFile(__dirname + '/SearchRequest.xml', function(err, data) {
        parser.parseString(data, function (err, result) {
            resultat = result['rss']['channel']['item'][index];
            //console.log(resultat); // works
            callback(resultat);
        });
    });
}

var index = 1;
getItem(index, function(d){
  console.log(d);
});
Comments