0

在函数getweather()中,我确实从 Json 对象中获取了一些天气数据,并将该数据存储在变量data中。在该函数中,我可以处理 Json 数据,但是如何从getweather()外部访问数据?

如果我返回变量locationdata并不重要。变量位置不是 Json。

如何处理place变量以使其像在函数getweather()中一样工作?

var ajax = require('ajax');

var place;
place = getweather();

function getweather()
{
    // Make the request
    ajax(
    {
      url: 'http://api.openweathermap.org/data/2.5/weather?q=paris.fr', type: 'json'
   },
    function(data) 
    {
    // Success!
    console.log("Successfully fetched weather data!");

    // Extract data
        var location = data.name;
        return location;    

    },
    function(error) {
    // Failure!
    console.log('Failed fetching weather data: ' + error);
    }
  );    
}
4

1 回答 1

1

AJAX 中的 A 代表异步。您的代码中发生的情况是您试图place在对 api.openweather.org 的异步调用返回之前分配一个值。

您可以通过console.log(place);直接在之后放置一个语句来检查这一点place = getweather();None您会在看到之前返回的控制台中注意到Successfully fetched weather data!

这个问题在这篇文章中有详细描述。它建议围绕回调重构代码。

于 2015-08-17T18:13:35.293 回答