2016-11-26 63 views
0

創建公共變量你好這是我的NodeJS 命令行獲取當前位置的天氣。的NodeJS

// Index.js 
// Modules 
const program = require('commander'); 
const clear = require('clear'); 
const chalk = require('chalk'); 
const request = require('ajax-request'); 
const fs = require('fs'); 
const json = require('read-data').json; 
const jsonfile = require('jsonfile') 

// Http Request to freegeoi.net 
request({ 
    url: "http://freegeoip.net/json/", 
    method: "GET", 
    data: { 
    format: "json" 
    }, 
}, function(err, res, body) { 

    // Parse the result 
    const data = JSON.parse(body); 

    // Extracting coordinates from data 
    let lat = data.latitude; 
    let long = data.longitude; 
}); 

// forecase key 
const key = "***********************"; 
// full forecast api url 
const url = `https://api.darksky.net/forecast/${key}/${lat},${long}`; 

問題是這樣的:我想變出要求功能LAT

我該怎麼做?

回答

3

你可以改變let lat = ...var lat = ...因爲let範圍到最近{}塊,其中爲var全球範圍 - 但這是一般不好的做法。

一個更好的選擇是調用另一個函數在請求回調結束:

function processLatLong(lat, long) { 
    //do something with lat long 
} 

request({ 
    url: "http://freegeoip.net/json/", 
    method: "GET", 
    data: { 
    format: "json" 
    }, 
}, function(err, res, body) { 

    // Parse the result 
    const data = JSON.parse(body); 

    // Extracting coordinates from data 
    let lat = data.latitude; 
    let long = data.longitude; 
    processLatLong(lat, long); 
});