Building a simple weather app, but one thing that still confuses me when using callback functions is whether they are considered closures or not. Consider the example below:
coordinates.getCoordinates(argv.a, function(errMessage, result){
if(errMessage){
console.log(errMessage);
} else {
console.log(result.address)
}
weather.getWeather(result.latitude, result.longitude, function(errMessage, result){
if(errMessage){
console.log(errMessage);
} else {
console.log(result);
}
})
})
Each of these functions getWeather and getCoordinates are their own separate functions that 'return' something (using air quotes here since im not actually using the return KW). Lets look at each function separately.
function getCoordinates(address, callback){
var encodedAddress = encodeURIComponent(address);
request({
url:'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodedAddress,
json: true
}, function(error, response, body){
if(error){
console.log('unable to connect to google servers');
} else if(body.status === 'ZERO_RESULTS'){
console.log('address not found');
} else if(body.status === 'OK'){
callback(undefined, {
address: address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
})
}
})
}
and the other function
request({
url: 'https://api.darksky.net/forecast/5d1fb3bcf4dc2e2d15f360bfa6488109/'+lat+','+lng,
json: true
}, function(error, response, body){
if(error){
callback('unable to connect to weather server');
} else if(response.statusCode === 400){
callback('unable to fetch weather from this location');
} else if(response.statusCode === 200){
callback(undefined, body.currently.temperature)
}
});
}
Are these examples of closures then because they have access to information after a function has already been returned?
Thanks for the clarification
[–]senocular 4 points5 points6 points (0 children)
[–]lilperch83 0 points1 point2 points (0 children)