I have the problem of a function returning a variable as "undefined" where the function call is made even when I can read the value of the variable inside the function in NodeJs. Well I understood that it could be a problem of asynchronous calls in Javascript and that I should be using call backs and that has been answered before here but I cant figure it out myself how it works in my case.
They are all in the same Js File and there is nothing wrong with the querying the fuseki server as I can read the output of the query in the function.
Can somebody help me out? Thanks in advance!
APP.js
FUNCTION
function fuseki(type,query){
var optionsKB = {
method: 'post',
body: query,
json: true, // Use,If you are sending JSON data
url:"",
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept':'application/sparql-results+json,*/*;q=0.9'
}
};
if (type == "query")
{ var result;
optionsKB.url = "http://127.0.0.1:3032/iii2017/query";
request(optionsKB, function (err, res, body) {
if (err) {
console.log('Error querying the knowledge base', err);
return;
}
//console.log(body);
var str = body.results.bindings[0].variable.value;
result = str.split("#")[1];
console.log("From function:", result); //PRINTS RESULT CORRECTLY
return result;
});
}
}
FUNCTION CALL
var getNeighQuery = "PREFIX iii:<http://manufacturing.com/ontology.owl#> SELECT * WHERE {iii:zone_3_7 iii:hasNeighbour ?neighbour.}"
var neighbour = fuseki("query",getNeighQuery); //queries the fuseki with the query obtained in the previous step to obtain
console.log('neighbour: ', neighbour); //PRINTS "undefined"