Question

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?

Était-ce utile?

La solution

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)
})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top