2016-11-21 73 views
-1

我當前正在運行的代碼 -阿比JSON返回「未定義」

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); 

和我期待的15的響應,因爲我引用返回

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

的API雖然我只得到Undefined的迴應。 爲什麼? 在此先感謝。

+0

異步函數調用 – Satpal

回答

1

您需要將console.log放入回調函數中,否則將在回調函數返回前從服務器返回數據。

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); 
}) 
+1

我們不需要另一個回答這個問題。 :-) –