I am trying to return an object that I am constructing from data obtained from a call to a third party API. I am using the Request(https://github.com/mikeal/request) module to accomplish the same.
However, I want to return this object from the callback function.
My request call is a part of a javascript function and I want this outer function to be able to return the newly constructed object. I am facing problem due to non-blocking nature of node.js as whenever I try to return object from the outer function, it returns an empty object because the callback function has not yet contructed the object.
How can I achieve this?
function getData(url){
var myWeatherData = new Object();
var data;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
data = JSON.parse(body);
myWeatherData.locationName = data.current_observation.display_location.full;
myWeatherData.weather = data.current_observation.weather;
myWeatherData.temperature_string = data.current_observation.temperature_string;
myWeatherData.relative_humidity = data.current_observation.relative_humidity;
myWeatherData.wind_string = data.current_observation.wind_string;
myWeatherData.feelslike_string = data.current_observation.feelslike_string;
}
return myWeatherData; // THIS IS A RETURN FROM CALL BACK
});
// return myWeatherDataArr; -- THIS RETURNS AN EMPTY
};
Copyright Notice:Content Author:「Abk」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/25510410/returning-a-object-from-call-back-function-so-that-a-wrapping-function-can-retu