I have this function in my node js application. I give it the user's location in latitude and longitude, a radius, and a keyword to search. There is an node module named googleplaces that I've been using to pass these value to the GooglePlace API.
function placesRequest(radius, lat, lon, keyword){
var conductor = new googlePlaces(googlePlacesAPIKey, "json");
var parameters = {
radius: radius,
location:[lat, lon],
types:"restaurant",
query:keyword
};
conductor.placeSearch(parameters, function(error, response) {
if (error) throw error;
console.log(response.results) //for debugging
if(response.status=="ZERO RESULTS") return "{results:0}";
return response.results;
});
}
I'm still relatively new to node js and I've been looking up on how to modularize the functions, but I'm not entirely sure how it works. The furthest I've gotten was rewriting the function separately. Is there a quick way of retrieving the response.results data or should I just curl the request?
You need to provide a callback to placesRequest in order to get the result:
function placesRequest(radius, lat, lon, keyword, callback){
var conductor = new googlePlaces(googlePlacesAPIKey, "json");
var parameters = {
radius: radius,
location:[lat, lon],
types:"restaurant",
query:keyword
};
conductor.placeSearch(parameters, function(error, response) {
/*
Consider passing the error to the callback
if (error) throw error;
console.log(response.results) //for debugging
if(response.status=="ZERO RESULTS") return "{results:0}";
*/
callback(response.results);
});
}
So you call placesRequest like this:
placesRequest(1,2,3,'abc', function (results) {
// do something with the results
});
Yup it's ugly and it can get complicated when you star dependending on multiple returns. But for a lot of cases that's enough.
For complex cases you can use some abstractions like:
I found the solution but I should mention more about the project in order to warrant the solution. The function mentioned above is a simple places search was supposed to:
Take the users input (latitude, longitude, radius, keyword)
Pass those values to google places
Return the data returned by Google
The data that was recieved would then be sent as a http response to an intial http request that would deliver all the data needed. Because of the nature of the application, it would need to handle different request types (map search, user profile edit, etc) so I implemented a seperate function with a switch case in it.
THE SOLUTION:
Take the switch case from the function and insert it into the function that runs the http server. Then, take the placesRequest function and put that into the switch case and just write the response from there. It's not the prettiest solution but it works.