好的!有些东西正在逃避我。
我的顶点项目旨在为我们在家里经营的民宿增值。我们希望为客人提供一个工具,让他们能够了解我们地区现在和下周的天气,以便他们可以计划在该地区冒险时穿什么。我们希望他们能够查找本地的餐馆并找到评论,以帮助他们决定去哪里吃饭(我们是一家民宿,我们不向他们提供食物)。最后,我们希望他们能够查找本地所有的“要去的地方”和“要看的东西”。
所有这些功能都基于地理位置,需要我们的地址作为基础和我们的位置坐标。
我正在尝试构建一个将返回三件事的模块:
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
下面是有问题的代码:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'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;</code></pre>
</div>
</div>
最佳答案
您正在编写异步代码。当您导出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()
执行某些操作。
关于node.js - 我正在尝试在 node.js 项目中的模块之间传递数据,但我遗漏了一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50379894/