0
function searchCoords(){
  var result = result;
  connection.query('SELECT * FROM monitoring', function(err, result){
    if(err){
      console.log(err);
    }
    return{
      result: result};
    });
}

That's my code. I'm using that code to find the last coordinates of some devices and display them in google maps. but i need to first be able to access the array from the ouside so i can do something like:

myModule.searchCoords().result

or myModule.searchCoords()().result

However I still can't access the array (result) from the outside function, let alone from another module. I've been reading on closures, scopes, nested functions, anonymous functions, etc. but i still can't find the solution. What am i doing wrong?

1 Answer 1

1

Problem is, that the query is asynchronous, so it can't return a value in the normal flow. If you pass a function when you call searchCoords, then that function can be called after the results come back - which could be after a long delay. This is necessary to prevent the program flow from being blocked whilst potentially long operations are in process.

// accept a callback function to execute after getting results...
function searchCoords(callback){
  var result = result;
  connection.query('SELECT * FROM monitoring', function(err, result){
    if(err){
      console.log(err);
    }
    // run the callback function, passing the results...
    callback({result: result});
  });
}

// call like this...
// pass a function accepting results object that will be executed as callback
// once results have been returned...
searchCoords(function(resultsObject){
    console.log(resultsObject.result)
})
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, that worked, now i can call the variable from the outside and display it like: database.searchCoords(function(resultsObject){ resultsObject.result; }); there's still one more thing i'd like to do... is there a way to convert the callback function into a variable that will return exactly the same as result so i can call it from the google maps api like: variable[0][1]
I am not sure exactly what you mean - I think you should perhaps ask a question on stack overflow ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.