[英]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.