簡體   English   中英

NodeJS 函數沒有返回數據

[英]NodeJS no data returned from function

我正在開發一個簡單的天氣應用程序,它使用僅包含城市名稱的 mysql 數據庫。 然后我在數據庫中查詢所有名稱,然后向 openweathermap 的 API 發送天氣信息請求。

function getCities() {
  con.connect();
  con.query(('SELECT city_name FROM cities'), (err, res) => {
    console.log(res);
    getWeather(cities);
  });
};

async function getWeather(cities) {
  var data = [];
  for (var i = 0; i < cities.length; i++) {
    var url = `http://api.openweathermap.org/data/2.5/weather?q=${cities[i].city_name}&units=metric&appid=271d1234d3f497eed5b1d80a07b3fcd1`;
    await request(url, (err, res, body) => {
      var json = JSON.parse(body);
      var weather = {
        city: json.name,
        temperature: json.main.temp,
        description: json.weather[0].description,
        icon: json.weather[0].icon
      };
      data.push(weather);
    });
  }
  console.log(data);
}

getCities()函數按預期工作並返回所有城市,但錯誤發生在 getWeather 函數中,特別是這些錯誤:

Desktop/WeatherApp/node_modules/request-promise-core/lib/plumbing.js:130
            throw thrownException;
            ^

TypeError: Cannot read property 'temp' of undefined
    at Request.request [as _rp_callbackOrig] (/home/kristijan/Desktop/WeatherApp/app.js:60:41)
    at Request.plumbing.callback (/home/kristijan/Desktop/WeatherApp/node_modules/request-promise-core/lib/plumbing.js:76:39)
    at Request.RP$callback [as _callback] (/home/kristijan/Desktop/WeatherApp/node_modules/request-promise-core/lib/plumbing.js:46:31)
    at Request.self.callback (/home/kristijan/Desktop/WeatherApp/node_modules/request/request.js:185:22)
    at Request.emit (events.js:182:13)
    at Request.<anonymous> (/home/kristijan/Desktop/WeatherApp/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:182:13)
    at IncomingMessage.<anonymous> (/home/kristijan/Desktop/WeatherApp/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:273:13)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

據我所知,它是在從 API 獲取結果之前跳轉到箭頭函數的內部?

如果您正在等待的函數結果返回一個承諾, await只會等待異步操作。 request()函數不返回承諾(它與您傳遞給它的回調一起工作)因此await不會等待該結果。 您可以改用request-promise庫,它會返回一個 promise 並且您不會將回調傳遞給它。

這是一個例子:

const rp = require('request-promise');

async function getWeather(cities) {
  let data = [];
  for (let i = 0; i < cities.length; i++) {
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${cities[i].city_name}&units=metric&appid=271d1234d3f497eed5b1d80a07b3fcd1`;
    let body = await rp(url);
    let json = JSON.parse(body);
    let weather = {
        city: json.name,
        temperature: json.main.temp,
        description: json.weather[0].description,
        icon: json.weather[0].icon
    };
    data.push(weather);
  }
  console.log(data);
}

請注意,您還可以讓請求 API 自動為您解析 JSON:

const rp = require('request-promise');

async function getWeather(cities) {
  let data = [];
  for (let i = 0; i < cities.length; i++) {
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${cities[i].city_name}&units=metric&appid=271d1234d3f497eed5b1d80a07b3fcd1`;
    let json = await rp({uri:url, json: true});
    let weather = {
        city: json.name,
        temperature: json.main.temp,
        description: json.weather[0].description,
        icon: json.weather[0].icon
    };
    data.push(weather);
  }
  console.log(data);
}

編輯 2020 年 1 月 - request() 模塊處於維護模式

僅供參考, request模塊及其衍生產品(如request-promise )現在處於維護模式,不會積極開發以添加新功能。 您可以在此處閱讀有關推理的更多信息。 此表中有一個備選方案列表,並對每個備選方案進行了一些討論。 我自己一直在使用got()並且它從一開始就使用 promises 構建並且易於使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM