[英]How to pass values from function to an array
我正在執行一個OpenWeatherMap項目,任務是從API調用中獲取溫度。 我無法弄清楚如何將溫度值從“ for”循環傳遞到在頂部定義的“溫度”數組:
const request = require('request');
let apiKey = 'xxxxxxxxx';
let url = `http://api.openweathermap.org/data/2.5/forecast?lat=30.2240897&lon=-92.0198427000000&units=imperial&${apiKey}`
let temperature = new Array();
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
let data = JSON.parse(body);
let weatherList = data.list;
for (i=0; i<weatherList.length; i++) {
temperature[i] = weatherList[i].main.temp;
}
return temperature;
}
});
關於如何將我從for循環中收集的值推送到“溫度”數組的任何幫助都將非常有用!
由於request()是一個異步調用,您的進一步處理取決於溫度數組的值,因此您需要在該請求回調內訪問該代碼的代碼。 我懷疑您可能在調用請求函數的異步代碼塊之后立即訪問溫度數組。
var arr = new Array(); setTimeout(function(){ arr.push(10); console.log("inside async block"); console.log(arr); }, 1000); console.log("immediately after async block"); console.log(arr);
api使用ajax調用或獲取您正在使用的任何方法,需要花費一些時間才能從服務器返回響應。 由於您正在進行的api調用是異步的,因此您嘗試在ajax調用完成之前分配溫度值。 這就是溫度始終為空的原因。 您需要使用一些回調從api響應內部訪問溫度值。
像這樣:
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
let data = JSON.parse(body);
let weatherList = data.list;
for (i=0; i<weatherList.length; i++) {
temperature[i] = weatherList[i].main.temp;
}
useTemp(temperature);
}
});
useTemp(temperature)
{
//Do something with temperature
}
我認為您正在做的一些事情阻礙了您。
首先:Request不是基於Promise的庫,因此我們需要等待響應才能返回。 我們需要創建一個Promise供我們等待。
第二:ES6為我們帶來了使之可讀且可重復的簡便方法。
以下是一些確切的調用示例,但它們使用不同的方法完成:
/**
* Must await for a Promise, request does not natively return a Promise, so create one
* */
const request = require('request');
let temperature = new Array();
module.exports.getWeatherRequest = async () => {
// Create Our Returned Promise
function doRequest(url) {
return new Promise((resolve, reject) => {
request(url, function (error, res, body) {
if (error) {
reject(error)
}
resolve(JSON.parse(body));
})
})
}
/*
* Call Our Promise
**/
let resp = await doRequest(url);
/*
* For/of Loops through Object for only temps
* Push each value into temperature
**/
for (let temps of resp.list) {
temperature.push(temps.main.temp)
}
/*
* Outcome
*/
console.log('Temps : ', temperature)
}
ES6以及Node-Fetch:
const fetch = require('node-fetch');
module.exports.getWeatherFetch = async () => {
let weather = await fetch(url)
.then(blob => blob.json())
.then(data => data)
.catch(error => { console.error(error) })
console.log('Weather Response ', weather)
// Here you'll handle the data/for of loop
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.