简体   繁体   English

如何正确导出从NodeJS中的API调用检索到的值

[英]How to properly export values retrieved from an API call in NodeJS

I'm simply trying to get the latitude and longitude from a geolocation API so I can pass the data into another API call to get the weather. 我只是想从地理位置API获取纬度和经度,以便将数据传递到另一个API调用中以获取天气。 How do I make it so the values are assigned to the global variables? 我该如何将这些值分配给全局变量? As of right now I'm getting undefined. 截至目前,我变得不确定。

I've moved the variables in and out of the function. 我已经将变量移入和移出了函数。 Tried to return the values within the function and export the function itself. 试图返回函数内的值并导出函数本身。

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;

To export some value retrieved by an asynchronous call you need to wrap them in a Promise or a callback . 要导出异步调用检索的某些值,您需要将它们包装在Promise回调中

Using the promise style it will look like this 使用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);
    }
  });
});

Then you can get the "wrapped" values like this 然后,您可以像这样获取“包装”

// 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);

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

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