【问题标题】:How to properly export values retrieved from an API call in NodeJS如何正确导出从 NodeJS 中的 API 调用检索到的值
【发布时间】:2024-01-06 02:29:01
【问题描述】:

我只是想从地理定位 API 获取纬度和经度,这样我就可以将数据传递给另一个 API 调用来获取天气。如何将值分配给全局变量?到现在为止,我越来越不确定了。

我已经将变量移入和移出函数。试图返回函数内的值并导出函数本身。

const https = require('https');

const locationApiKey = 
"KEY GOES HERE";

let lat;
let lon;
let cityState;

module.exports = location = https.get(`https://api.ipdata.co/?api-key=${locationApiKey}`, response => {
        try {
            let body = " ";

            response.on('data', data => {
                body += data.toString();
            });
            response.on('end', () => {
                const locationData = JSON.parse(body);
                // console.dir(locationData);
                lat = locationData.latitude;
                lon = locationData.longitude;
            });
        } catch (error) {
            console.error(error.message);
        }
    });

module.exports.lat = lat;
module.exports.lon = lon;

【问题讨论】:

  • http.get 是一种异步方法。您应该将其转换为承诺并在异步函数中等待它,或者使用回调中的值

标签: javascript node.js ip-geolocation


【解决方案1】:

要导出通过异步调用检索到的某些值,您需要将它们包装在 Promisecallback 中。

使用promise样式会是这样的

// File: api.js
module.exports = () => new Promise((resolve, reject) => {
  https.get(`https://api.ipdata.co/?api-key=${locationApiKey}`, response => {
    try {
      let body = " ";

      response.on('data', data => {
        body += data.toString();
      });
      response.on('end', () => {
        const { latitude, longitude } = JSON.parse(body);
        resolve({lat: latitude, lon: longitude});
      });
    } catch (error) {
      reject(error);
    }
  });
});

然后你就可以像这样得到"wrapped" 值了

// File: caller.js
const getLocation = require('./api.js');

getLocation()
  .then(({lat, lon}) => {
    // The values are here

    console.log(`Latitude: ${lat}, Longitude: ${lon}`)
  }))
  .catch(console.error);

【讨论】:

    最近更新 更多