【问题标题】:How to store JSON response in variable in Node.js? [duplicate]如何将 JSON 响应存储在 Node.js 中的变量中? [复制]
【发布时间】:2017-05-22 19:24:26
【问题描述】:

我正在努力从 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 响应存储到一个变量中。然后我将根据当前温度撰写推文。

【问题讨论】:

  • 也许你可以在回调中发推文?
  • 一个常见的异步问题,当您尝试打印 curTemp 时,该变量很可能未定义,因为 HTTP 请求尚未完成。所以使用回调或承诺或将依赖于curtemp 的代码包装到同一范围内。

标签: javascript json node.js openweathermap


【解决方案1】:

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

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

【讨论】:

  • 大声笑..就这么简单吗?
  • 哈哈 .. 我正要向你展示在 nodejs 中你应该如何思考。
【解决方案2】:

请求是异步的。如果你想以这种方式编写异步代码,你应该使用返回 Promise 的 API,例如axios。然后您可以使用async/await 编写您的代码。

【讨论】:

  • 你能用代码解释一下吗?我对节点完全陌生。
  • @SantoshKumar 这不是节点的事情。您可能想事先了解更多关于 javascript 本身的信息。开始在 Mozilla 的开发者网络上了解 Promise 和异步的东西。
  • 请不要回答骗子。改为关闭标志。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多