Javascript 如何在Node.js中的变量中存储JSON响应?

Javascript 如何在Node.js中的变量中存储JSON响应?,javascript,json,node.js,openweathermap,Javascript,Json,Node.js,Openweathermap,我正在努力从API获取响应,并将其保存在变量中,以便在Node.js中进一步使用它。也许我不知道这种语言是如何运作的。问题是: // Objective, get current temperature of New Delhi in celcius var request = require('request'); var url = "http://api.openweathermap.org/data/2.5/weather?id=1261481&appid=#####&

我正在努力从API获取响应,并将其保存在变量中,以便在Node.js中进一步使用它。也许我不知道这种语言是如何运作的。问题是:

// Objective, get current temperature of New Delhi in celcius

var request = require('request');

var url = "http://api.openweathermap.org/data/2.5/weather?id=1261481&appid=#####&units=metric";

request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    curTemp = JSON.parse(body).main.temp;  // curTemp holds the value we want
  }
})

// but I want to use it here
console.log(curTemp);

我想将openweathermap(即
body.main.temp
)的JSON响应存储到一个变量中。然后,我将根据当前温度撰写一条tweet。

请求是异步的。如果您希望以这种方式编写异步代码,则应使用返回承诺的API,例如。然后可以使用来编写代码。

在Node.js中,所有内容都是关于回调(或稍后需要调用的函数)。 因此,您只需创建一个tweet函数,并在获得数据时调用它

var request = require('request');
var url = "http://api.openweathermap.org/data/2.5/weather?id=1261481& appid=#####&units=metric";
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    curTemp = JSON.parse(body).main.temp;  // curTemp holds the value we want
    tweet(curTemp)
  }
})

// but I want to use it here
function tweet(data){
    console.log(data)
}

考虑到这不是异步编码的好方法。

您能用代码解释一下吗?我对node完全是新手。@SantoshKumar这不是node的事。您可能希望事先了解更多关于javascript本身的信息。开始学习mozilla开发人员网络上的承诺和异步内容。请不要回答重复。标记为关闭。也许您可以在回调内tweet?这是一个常见的异步问题,当您尝试打印
curTemp
时,变量很可能未定义,因为HTTP请求尚未完成。因此,使用回调或承诺,或者将依赖于
curtemp
的代码包装到相同的作用域中。。就这么简单吗?哈哈。。我只是想向你展示你应该如何用nodejs思考。