-1

I am currently running the code-

const request = require('request')
const apiKey = 'XXXXXXXXXXXXXX'

var dat;
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
    q: '-34.48,150.92',
    format: 'json',
    apiKey
}
request({ url, qs }, (err, response, body) => {
    if (err)
        return console.error(err)
    if (response.statusCode != 200)
        return console.error('status code is', response.statusCode)
    body = JSON.parse(body)
    dat = body.data.hourly[0].tempC


})
console.log(dat);

and I am expecting a response of 15 as I am referencing the API that returns

{
"data": {
    "request": [],
    "weather": [{ 
        "date": "2016-11-20",
        "astronomy": [],
        "maxtempC": "27",
        "maxtempF": "80",
        "mintempC": "15",
        "mintempF": "58",
        "hourly": [{
            "time": "0",
            "tempC": "15",
...

Although I am only getting the response of Undefined. Why? Thanks in advance.

brennanyoung
  • 6,243
  • 3
  • 26
  • 44
Samuel Aubin
  • 1,653
  • 2
  • 9
  • 6

1 Answers1

2

You need to put the console.log inside the callback, otherwise it will execute before the callback returns with the data from the server.

const request = require('request')
const apiKey = 'XXXXXXXXXXXXXX'

var dat;
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
q: '-34.48,150.92',
format: 'json',
apiKey
}
request({ url, qs }, (err, response, body) => {
if (err)
return console.error(err)
if (response.statusCode != 200)
return console.error('status code is', response.statusCode)
body = JSON.parse(body)
dat = body.data.hourly[0].tempC
console.log(dat);
})
Joe
  • 2,500
  • 1
  • 14
  • 12