I have read the following questions and corresponding insightful answers and understood how asynchronous call back functions work-
How do I return the response from an asynchronous call?
How to return value from an asynchronous callback function?
Returning value from asynchronous JavaScript method?
But still not able to successfully return the appropriate vaule. Following is the code -
function foo(callback){
request('some-url.json', function (error, response, body) {
//Check for error
if(error){
//error body
}
//Check for right status code
if(response.statusCode !== 200){
//response body
}
//All is good. Print the data
var data = JSON.parse(body);
callback(data.some-property);
});
}
module.exports = {
foo:foo(function(result){
console.log(result); //works
return result; //doesn't work
}),
};
I am able to get the expected result in the console log but still its not able to return the value.
Error: TypeError: Property 'foo' of object #<Object> is not a function
Problem:
1.Is the callback function execution correct?
2.What should I do to return the value successfully?
Edit: Finally after an extensive conversation with Paarth I have decided to resort to promise.js which will allow me to indirectly return the value I seek from my function. For further resources regarding promise.js -
https://gist.github.com/domenic/3889970
http://colintoh.com/blog/staying-sane-with-asynchronous-programming-promises-and-generators