第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

API 調(diào)用上的 Node.js 循環(huán)

API 調(diào)用上的 Node.js 循環(huán)

哈士奇WWW 2021-12-12 17:51:04
我正在嘗試使用不同的參數(shù)進(jìn)行少量 API 調(diào)用。獲取數(shù)據(jù)并按天、城市最高溫度、城市最低溫度和有雨城市將其轉(zhuǎn)換為 CSV 文件。API 示例:https : //samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22我有以下帶有城市和 api 密鑰的對(duì)象:const cities = {    0: ['Jerusalem', 'il'],    1: ['New York', 'us'],    2: ['Dubai', 'ae'],    3: ['Lisbon', 'pt'],    4: ['Oslo', 'no'],    5: ['Paris', 'fr'],    6: ['Berlin', 'de'],    7: ['Athens', 'gr'],    8: ['Seoul', 'kr'],    9: ['Singapore', 'sgp'],}const apiKey = "[retracted]";這是我想動(dòng)態(tài)迭代的 API 調(diào)用,目前我只在第一個(gè)對(duì)象參數(shù)上運(yùn)行它并最終將信息推送到天氣,以便我可以操縱數(shù)據(jù)按天(前 5 天)對(duì)其進(jìn)行排序,然后顯示城市氣溫最高、氣溫最低的城市和所有下雨的城市:request(`http://api.openweathermap.org/data/2.5/forecast?q=${cities[1][0]},${cities[1][1]}&mode=json&appid=${apiKey}`, (error, response, body) => {    let data = JSON.parse(body);        let weather = {        0: [day, highTemp, lowTemp, rain],        1: [day, highTemp, lowTemp, rain],        2: [day, highTemp, lowTemp, rain],        3: [day, highTemp, lowTemp, rain],        4: [day, highTemp, lowTemp, rain],    }    // day 1    console.log(data['city']['name']);    console.log(data['list'][0].dt_txt);    console.log(data['list'][0].main['temp']);    // day 2    console.log(data['city']['name']);    console.log(data['list'][8].dt_txt);    console.log(data['list'][8].main['temp']);    // day 3    console.log(data['city']['name']);    console.log(data['list'][16].dt_txt);    console.log(data['list'][16].main['temp']);    // day 4    console.log(data['city']['name']);    console.log(data['list'][24].dt_txt);    console.log(data['list'][24].main['temp']);    // day 5    console.log(data['city']['name']);    console.log(data['list'][32].dt_txt);    console.log(data['list'][32].main['temp']);});我嘗試使用帶有對(duì)象中的鍵的 for 循環(huán),但不幸的是它不顯示數(shù)據(jù),錯(cuò)誤原因未定義。
查看完整描述

2 回答

?
泛舟湖上清波郎朗

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊

我建議使用 response-promise-native 來(lái)允許使用 async/await。這將允許我們遍歷城市列表并將每個(gè)城市的天氣數(shù)據(jù)附加到城市詳細(xì)信息(名稱和國(guó)家/地區(qū))。


一旦我們有了這些數(shù)據(jù),我們就可以進(jìn)行您提到的處理,我們可以獲得最高和最低溫度(請(qǐng)注意,溫度以開爾文為單位,因此我們將轉(zhuǎn)換為攝氏度。)


重要的是要指出我按本地日期分組,如果您希望按UTC 日期分組,那么您應(yīng)該更改該行:


let timeOffset = entry.dt + result.weatherResponse.city.timezone;


let timeOffset = entry.dt;

這是解釋數(shù)據(jù)的一種稍微不同的方式!


我現(xiàn)在已更新為按日期分組,結(jié)果如下所示:


按當(dāng)?shù)厝掌诜纸M:


Date,Highest Temperature,Lowest Temperature,Cities With Rain

2019-11-01,Dubai,Oslo,"Paris,Berlin"

2019-11-02,Singapore,Oslo,"Lisbon,Paris,Berlin,Singapore"

2019-11-03,Singapore,Oslo,"Lisbon,Paris,Berlin,Athens,Singapore"

2019-11-04,Singapore,Oslo,"Lisbon,Paris,Berlin,Athens"

2019-11-05,Singapore,Oslo,"Lisbon,Paris,Berlin,Singapore"

2019-11-06,Singapore,Oslo,"Paris,Berlin,Singapore"

2019-11-07,Seoul,Seoul,""

按 UTC 日期分組:


Date,Highest Temperature,Lowest Temperature,Cities With Rain

2019-11-01,Dubai,Oslo,"Paris,Berlin"

2019-11-02,Singapore,Oslo,"Lisbon,Paris,Berlin,Singapore"

2019-11-03,Singapore,Oslo,"Lisbon,Paris,Berlin,Athens,Singapore"

2019-11-04,Singapore,Oslo,"Lisbon,Paris,Berlin,Athens"

2019-11-05,Singapore,Oslo,"Lisbon,Paris,Berlin,Singapore"

2019-11-06,Singapore,Oslo,"Paris,Berlin,Singapore"

代碼:


const rp = require("request-promise-native");


const cities = {

    0: ['Jerusalem', 'il'],

    1: ['New York', 'us'],

    2: ['Dubai', 'ae'],

    3: ['Lisbon', 'pt'],

    4: ['Oslo', 'no'],

    5: ['Paris', 'fr'],

    6: ['Berlin', 'de'],

    7: ['Athens', 'gr'],

    8: ['Seoul', 'kr'],

    9: ['Singapore', 'sgp'],

}



async function getWeatherForCities() {

    let results = [];

    for (let [city, countryCode] of Object.values(cities)) {

        console.log(`Getting weather for city: ${city}, country: ${countryCode}...`);

        let weatherResponse = await rp({ url: `http://api.openweathermap.org/data/2.5/forecast?q=${city},${countryCode}&mode=json&appid=${apiKey}`, json: true});

        results.push ({ city, countryCode, list: weatherResponse.list, weatherResponse });

    }


    let summary = results.map(res => {  

        return { city: res.city, countryCode: res.countryCode,

        maxTemperature: getMaxTemperatureCelsius(res.list),

        minTemperature: getMinTemperatureCelsius(res.list),

        totalRainfall: getTotalRainFall(res.list)

    }});


    console.log("Summary (over forecasting interval): ", summary);

    console.log("Result with the highest temperature: ", [...summary].sort((resA, resB) => resB.maxTemperature - resA.maxTemperature)[0]);

    console.log("Result with the lowest temperature: ", [...summary].sort((resA, resB) => resA.minTemperature - resB.minTemperature)[0]);

    console.log("Cities with rain: ", summary.filter(res => res.totalRainfall).map(res => res.city));


    // Group by date (local) and city

    let resultsGroupedByDateAndCity = {};

    results.forEach(result => {

        result.list.forEach(entry => {

            let timeOffset = entry.dt + result.weatherResponse.city.timezone;

            let date = new Date(timeOffset * 1000);

            date.setHours(0,0,0,0);

            let dateKey = date.toISOString().substring(0,10);

            if (!resultsGroupedByDateAndCity[dateKey]) resultsGroupedByDateAndCity[dateKey] = {};

            if (!resultsGroupedByDateAndCity[dateKey][result.city]) resultsGroupedByDateAndCity[dateKey][result.city] = [];

            resultsGroupedByDateAndCity[dateKey][result.city].push(entry);

        });

    });


    // Run through the keys.

    let csvLines = ["Date,Highest Temperature,Lowest Temperature,Cities With Rain"];


    for (let [date, obj] of Object.entries(resultsGroupedByDateAndCity)) {

        let dailySummary = Object.entries(obj).map(([city, dayList]) => {  

            return { city,

            maxTemperature: getMaxTemperatureCelsius(dayList),

            minTemperature: getMinTemperatureCelsius(dayList),

            totalRainfall: getTotalRainFall(dayList)

        }});


        console.log("Details for date " + date + ": ");

        let resultWithHighestTemperature = [...dailySummary].sort((resA, resB) => resB.maxTemperature - resA.maxTemperature)[0];

        let resultWithLowestTemperature = [...dailySummary].sort((resA, resB) => resA.minTemperature - resB.minTemperature)[0];

        let citiesWithRain = dailySummary.filter(res => res.totalRainfall).map(res => res.city);

        console.log("Result with the highest temperature: ", resultWithHighestTemperature);

        console.log("Result with the lowest temperature: ", resultWithLowestTemperature);

        console.log("Cities with rain: ", citiesWithRain);


        csvLines.push([date, resultWithHighestTemperature.city, resultWithLowestTemperature.city, '"' + citiesWithRain.join(",") + '"'].join(","));

    }


    console.log("CSV result:\n", csvLines.join("\n"));

}


function KelvinToCelsius(kelvin) {

    return (kelvin - 273.15);

}


// Return the max temperature for the forecast

function getMaxTemperatureCelsius(responseList) {

    // Get a list of the max temperatures for the forecast.

    const maxTemps = responseList.map(entry => Number(entry.main.temp_max));

    return KelvinToCelsius(Math.max(...maxTemps));

}


// Return the min temperature for the forecast

function getMinTemperatureCelsius(responseList) {

    // Get a list of the min temperatures for the forecast.

    const minTemps = responseList.map(entry => Number(entry.main.temp_min));

    return KelvinToCelsius(Math.min(...minTemps));

}


// Return the total rainfall for the forecast

function getTotalRainFall(responseList) {

    // Get a list of the min temperatures for the forecast.

    const rain = responseList.map(entry => { return entry.rain ? Number(entry.rain["3h"]): 0 });

    return rain.reduce((sum, val) => sum + val, 0)

}


getWeatherForCities();


查看完整回答
反對(duì) 回復(fù) 2021-12-12
?
慕姐4208626

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊

您可以使用它Promise.all來(lái)實(shí)現(xiàn)這一點(diǎn)。


Promise.all 返回一個(gè)單一的 Promise,當(dāng)作為可迭代對(duì)象傳遞的所有承諾都已解決或可迭代對(duì)象不包含任何承諾時(shí),該 Promise 會(huì)解決。


const getData = (url) => {

   return fetch(url)

    .then(data => data.json())

    .then(jsonData => jsonData)

    .catch(err => {

      console.log("Error while resolving the promise for url", url);        

    });  

}


let arr = [1, 2, 4, 5, 6, 7];


const cities = {

    0: ['Jerusalem', 'il'],

    1: ['New York', 'us'],

    2: ['Dubai', 'ae'],

    3: ['Lisbon', 'pt'],

    4: ['Oslo', 'no'],

    5: ['Paris', 'fr'],

    6: ['Berlin', 'de'],

    7: ['Athens', 'gr'],

    8: ['Seoul', 'kr'],

    9: ['Singapore', 'sgp'],

}


const apiKey = "[retracted]";


Promise.all(Object.keys(cities).map(id => {  

  let url = `http://api.openweathermap.org/data/2.5/forecast?q=${cities[id][0]},${cities[id][1]}&mode=json&appid=${apiKey}`;

  return getData(url);

  }))

 .then(results => {


        // results is an array that contains the result of each api call

        // so you can perform the action that you need here..


        results.map(result => {


          console.log(result['city']['name']);


        });


  })

  .catch(err => {

        // Handle the error..

        console.log(err);

  });  


查看完整回答
反對(duì) 回復(fù) 2021-12-12
  • 2 回答
  • 0 關(guān)注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)