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

标签 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=#####&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 响应存储到变量中。然后我将根据当前温度撰写一条推文。

最佳答案

在 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)
}

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

关于javascript - 如何在 Node.js 中的变量中存储 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41532678/

相关文章:

php - AJAX 值发送错误

c# - 无法将 json 解析为自定义对象列表

node.js - CentOS、Node.js、init.d、ENOENT,当应用程序自动启动时,无法在系统重新启动时打开或写入日志文件

javascript - 准备好的 SQL 语句中的 NodeJS MSSQL

json - 如何提高Haskell中使用JSON的便利性?

node.js - 我如何优化在不同操作系统上运行的网页抓取脚本

javascript - 从子组件访问父 prop/attribute

javascript - 我尝试在 p5.js 中保存 27 个图像,但只有 10 个保存到我的下载文件夹中。为什么所有文件都没有保存?

javascript - 使用javascript将一张透明图像叠加在另一张透明图像上

javascript - 在 Javascript 中加载 XML 数据时出错