I’m having troubles to return a value from a function that is inside an object’s method. How could I do this? Let me explain with code.
function ObjPerson() {
this.getPerson = function() {
function queryDB() {
//run query and pass result data to success or error functions
}
function success(data) {
//process data
return data;
}
function error(errorData) {
//process error
}
queryDB();
}
}
var person = new ObjPerson;
var userData = ObjPerson.getPerson();
The problem is that nothing is being returned from the getPerson() method. What would be the best way to do this?
Thanks!
Return the value if this is a synchronous function
But if this function is async, then you should be doing it a bit differently. Unfortunately you won’t be able to just call:
because by the time the assignment is made, your async call will likely not return yet… So your
userDataassignment should be assigned after the async call. (tell us what async lib are you using)Other code smells in your example
But your code has other smells as well. Your inner functions
queryDB,successanderrorfunctions are defined within closure and for the sake of readability they should be defined as local scope variables: