简体   繁体   English

如何将值从函数传递到数组

[英]How to pass values from function to an array

Im doing an OpenWeatherMap project with the task of grabbing the temperatures from the API call. 我正在执行一个OpenWeatherMap项目,任务是从API调用中获取温度。 I cannot figure out how to pass the temperature values from my 'for' loop to my 'temperature' array that I've defined at the top: 我无法弄清楚如何将温度值从“ 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;
  }

});

Any help on how to push the values I've gathered from my for loop to the 'temperature' array would be so helpful! 关于如何将我从for循环中收集的值推送到“温度”数组的任何帮助都将非常有用!

Since request() is an async call and your further processing depends on the value of temperature array, you need the code to access it, inside that request callback. 由于request()是一个异步调用,您的进一步处理取决于温度数组的值,因此您需要在该请求回调内访问该代码的代码。 I'm suspecting you might be immediately accessing the temperature array after the async block of code which is call to request function. 我怀疑您可能在调用请求函数的异步代码块之后立即访问温度数组。

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

The api calls using ajax or fetch whatever method you are using, takes time to return response from server. api使用ajax调用或获取您正在使用的任何方法,需要花费一些时间才能从服务器返回响应。 Since you are making an api call, which is asynchronous and you are trying to assign temperature value before ajax call is finished. 由于您正在进行的api调用是异步的,因此您尝试在ajax调用完成之前分配温度值。 That is the reason temperature is always empty. 这就是温度始终为空的原因。 You need to use some callback to access temperature value from inside api response. 您需要使用一些回调从api响应内部访问温度值。

Like this: 像这样:

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
}

I think you have a few things going on here that are holding you back. 我认为您正在做的一些事情阻碍了您。

First: Request is not a Promise based library, as such we need to wait on the response to return. 首先:Request不是基于Promise的库,因此我们需要等待响应才能返回。 We need to create a Promise for us to wait for. 我们需要创建一个Promise供我们等待。

Second: ES6 brings us easy ways to make this readable and repeatable. 第二:ES6为我们带来了使之可读且可重复的简便方法。

Below are a few examples of your exact call but done in different methods: 以下是一些确切的调用示例,但它们使用不同的方法完成:

/**
* 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 and with Node-Fetch: 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.

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