0

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"
Community
  • 1
  • 1
user0221441
  • 368
  • 4
  • 11
  • 1
    You're right. `request` is asynchronous, and you can't return `result` like that. [There are a number of ways to solve this issue](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call?rq=1). – Andy Nov 26 '17 at 13:47
  • I was looking for some help with my code in particular as I cant pass the what needs to be done after getting response from the fuseki server as a callback function. – user0221441 Nov 26 '17 at 14:08
  • Once you learn how to write the correct code _in general_, you can apply it to your code. The duplicate question will assist you with that. – Andy Nov 26 '17 at 14:09

0 Answers0