繁体   English   中英

我正在尝试在node.js项目中的模块之间传递数据,但是我丢失了一些东西

[英]I am trying to pass data between modules in a node.js project, but I'm missing something

好! 某种东西正在逃避我。

我的顶峰项目旨在为我们家中的BnB增加价值。 我们希望将一种工具放到客人的手中,使他们可以查看现在和下周的天气情况,以便他们计划在该地区进行探险时穿什么衣服。 我们希望他们能够在当地查找餐馆并找到评论,以帮助他们决定在哪里用餐(我们是一家BnB,我们不为他们喂食)。 最后,我们希望他们能够查找所有本地“去的地方”和“看的东西”。

所有这些功能都是基于地理位置的,需要我们的地址作为基础以及我们的位置坐标。

我正在尝试构建一个将返回三件事的模块:

geocode.loc (which is the human readable geocode location)
geocode.lat (which is the latitude associated with the location)
geocode.lng (which is the longitude associated with the location)

这些数据点将在我的整个应用程序中传递给我正在使用的其他API:

a 'weather' api to return local weather
a 'restaurants' api to return local restaurants
an 'attractions' api to return local attractions

下面是有问题的代码:


  
 
  
  
  
'use strict';
//  this module connects to the Google geocode api and returns the formatted address and latitude/longitude for an address passed to it

const request = require('request'),
    req_prom  = require('request-promise');

const config  = require('../data/config.json');

const geocode_loc = 'Seattle, WA';
const geocode_key = config.GEOCODE_KEY;

const options = {
    url: `https://maps.google.com/maps/api/geocode/json?address=${geocode_loc}&key=${geocode_key}`,
    json: true
};

let body = {};

let geocode = request(options, (err, res, body) => {
    if (!err && res.statusCode === 200) {
        body = {
            loc: body.results[0].formatted_address,
            lat: body.results[0].geometry.location.lat,
            lng: body.results[0].geometry.location.lng
        };
        return body;
    }
});


module.exports.geocode = geocode;

您正在编写异步代码。 在您导出geocode ,该值尚未设置。

您应该导出一个函数,而不是导出geocode值。 该函数应采用回调(就像request一样)或使用Promises或使用async / await。

这就是我的写法:

let geocode = () => {
  return new Promise((rej, res) => {
    request(options, (err, res, body) => {
    if (!err && res.statusCode === 200) {
      const body = {
        loc: body.results[0].formatted_address,
        lat: body.results[0].geometry.location.lat,
        lng: body.results[0].geometry.location.lng
      };
      res(body);
    }
  }
});

然后,从其他模块中,您可以调用地址解析函数,并在请求完成后使用then()进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM