创建公共变量Nodejs

时间:2016-11-26 15:09:37

标签: javascript jquery node.js npm

您好我的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 long

我该怎么做?

1 个答案:

答案 0 :(得分: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);
});