4.4 Callback Functions & APIs

Callbacks

We are going to write a synchronous function that takes a callback.

var getUser = (id, callback) => {
var user = {
id : id,
name : "Jude"
};
setTimeout(() => { callback(user); }, 3000)
}
0
getUser(31, (user) => {
console.log(user);
});

Use API from browser

https://maps.googleapis.com/maps/api/geocode/json?address=uwaterloo

Request Module

To make HTTP request, we are going to use the Request module.
Go to npm request for detail info.

const request = require('request');
request({
url: "https://maps.googleapis.com/maps/api/geocode/json?address=uwaterloo",
json: true // convert string to Json for you
}, (err, res, body)=> {
console.log(body);
})

We get the address info:

$ node app.js
{ results:
[ { address_components: [Array],
formatted_address: '200 University Ave W, Waterloo, ON N2L 3G1, Canada',
geometry: [Object],
place_id: 'ChIJ_8ztAq32K4gRF44mljnynd0',
plus_code: [Object],
types: [Array] } ],
status: 'OK' }

If you got OVER_QUERY_LIMIT error, go to http://links.mead.io/api-fix for help.