Skip to content

Instantly share code, notes, and snippets.

@auchomage
Last active May 29, 2016 23:28
Show Gist options
  • Save auchomage/80e8c7ce5debfb7b44343462ad802582 to your computer and use it in GitHub Desktop.
Save auchomage/80e8c7ce5debfb7b44343462ad802582 to your computer and use it in GitHub Desktop.
Struggling with the concepts of callbacks used together with apis (application programming interfaces)l
/*
Using accessing an external local file ie one on this computer
*/
var weather = require('./weather.js');
var location = require('./location2.js');
/*
weather(function(currentWeather) {
currentWeather;
});
location(function(location) {
// We want the following properties
// (1) city name (2) longitude + lattitude
console.log('city' + location.city);
console.log('long/lat' + location.loc);
});
*/
location(function (location){
if (!location){
console.log('Location is unknown!');
} else {
console.log('City name:' + location.city);
console.log('Long/lat: ' + location.loc);
}
});
/*
This file runs in association with app.js
*/
module.exports = function(callback){
var request = require('request');
var url = 'http://ipinfo.io';
/*
The request modules takes 2 arguments
The request module takes an object as an argument.
The object has two fields, a url key and a json key
*/
/*
body = visible data on the web page.
4 is the number of spaces to indent json data by
*/
request({url: url, json: true}, function(error, response, body){
if(error){
callback ();
} else {
// This is how you pass the 'body' argument
callback(body);
}
});
};
@auchomage
Copy link
Author

For file 'location2.js' is 'callback' mentioned on line 5 the same as callback referenced on lines 21 and 24? Why is callback on line 5 written as 'callback' without any brackets is ()?

@auchomage
Copy link
Author

Why is there no statement like function callback() {...} ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment