Closed alexpilugin closed 6 years ago
Try wrapping the url
portion of const request = tiny.get(url, (err, response) => {
in curly braces {}
:
'use strict';
var tiny = require('tiny-json-http')
const url =
"https://maps.googleapis.com/maps/api/geocode/json?address=Florence";
getData(url)
.then(data =>
console.log(
`City: ${data.results[0].formatted_address} -`,
`Latitude: ${data.results[0].geometry.location.lat} -`,
`Longitude: ${data.results[0].geometry.location.lng}`
)
)
.catch(error => {
console.log('Error: ', error);
});
function getData(url) {
// return new pending promise
return new Promise((resolve, reject) => {
const request = tiny.get({url}, (err, response) => {
if (err) {
console.log('Error', err);
reject(err);
} else {
const body = response.body;
console.log(body);
resolve(body);
}
});
})
}
Oh! Thank you. It works!
My pleasure - basically the module is expecting the url
to be part of an object, but you were passing it through as a string.
Hey @alexpilugin ! Just FYI that tiny-json-http
"natively" supports Promise
. If you don't supply a callback it'll return one for you.
Ex.
var tiny = require('tiny-json-http')
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=Florence'
function handler(data) {
var first = data.body.results[0]
console.log(
`City: ${first.formatted_address} -`,
`Latitude: ${first.geometry.location.lat} -`,
`Longitude: ${first.geometry.location.lng}`
)
}
tiny.get({url}).then(handler).catch(console.log)
Hi @brianleroux
Your version looks amazing but from first time I received:
TypeError: Cannot read property 'formatted_address' of undefined
at handler (/011-tiny-callback/index.js:18:23)
at process._tickCallback (internal/process/next_tick.js:109:7)
from second launch: $ node index.js it produced an expected result!
bizarre! was unable to repro that myself
@brianleroux Yes, it was only once. Sorry, I couldn't replicate this error as well.
np at all! lmk if you run into anything else or have any other questions. happy to help. 🙏