【问题标题】:How to get snekfetch results into an object?如何将 snekfetch 结果放入对象中?
【发布时间】:2019-06-05 22:24:46
【问题描述】:

我正在编写一个 discord.js 机器人并尝试使用 Node.js / snekfetch 调用天气 API。问题是我不知道如何将 API 返回的数据放入 javascript 对象中。我想做这样的事情:

let [country, ...city] = args;
let url = `http://api.openweathermap.org/data/2.5/forecast?q=${city},${country}&units=metric&APPID=${config.weatherID};`;

var weatherObject;
snekfetch.get(url).then(r => weatherObject = r.body);`

但显然这不起作用所以我做错了什么?看起来它应该非常简单,但我就是做不到。由于 snekfetch 似乎没有被广泛使用,我在谷歌上搜索的任何内容都没有任何帮助,而且我完全无法将我所了解的有关 Promise 的任何信息外推到这种情况。

编辑:澄清:

snekfetch.get(url).then(r => console.log(r.body));

完全按照预期将对象打印到控制台,而

snekfetch.get(url).then(r => weatherObject = r.body);
console.log(weatherObject);

打印未定义。 .then() 语句的工作方式有什么我遗漏的吗?

【问题讨论】:

  • 这不起作用并不明显。 什么不起作用?有错误吗? weatherObject 的价值是多少,您期望它是什么?您的代码没有明显损坏,因此如果没有更多信息,很难为您提供帮助。
  • 另外,snekfetch 作者已弃用该软件包并推荐使用 node-fetch 作为替代方案。
  • @Hydrothermal 感谢您的回复!我已经更新了我原来的问题,希望能澄清我正在尝试做的事情以及我得到的输出。我知道 node-fetch 是为了取代 snekfetch 但我已经在我的代码中的几个地方使用了后者,它在其他任何地方都可以正常工作,所以如果我能提供帮助,我会尽量避免切换。跨度>

标签: javascript node.js discord discord.js


【解决方案1】:

.then() 语句不会让程序等待它们完成,它们只是在它们附加到的 Promise 被解析后执行它们的代码。
这意味着您不能可靠地使用已在 Promise 中设置的值,因为 Promise 之后的代码可能会在该 Promise 解析之前执行。

您可以决定将其余代码移动到 .then() 语句中,或者使用 async/await
如果您在一个函数内部,您可以将其声明为 async function:,这样您就可以在其中使用 await 关键字。 await 使程序等待 Promise 解决,而不是 Promise,它返回您将在 .then() 函数中使用的值。
这是一个例子:

// Instead of using this: 
function getResult(args) {
  let [country, ...city] = args;
  let url = `http://api.openweathermap.org/data/2.5/forecast?q=${city},${country}&units=metric&APPID=${config.weatherID};`;

  var weatherObject;
  snekfecth.get(url).then(response => {
    weatherObject = response.body;
  });

  return weatherObject; // undefined :(
}

// You could write it like this:
async function getResult(args) {
  let [country, ...city] = args;
  let url = `http://api.openweathermap.org/data/2.5/forecast?q=${city},${country}&units=metric&APPID=${config.weatherID};`;

  let response = await snekfecth.get(url);
  var weatherObject = response.body;

  return weatherObject; // right value
}

【讨论】:

  • 这几乎可以工作,但现在 weatherObject 的值作为“Promise { }”打印到控制台。我还缺少什么吗?
  • 哎呀没关系,通过将其余代码移动到 getResult 函数来让它工作!非常感谢您的帮助^^
  • 很高兴听到这个消息:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 2018-01-13
  • 2020-07-25
  • 2018-12-03
相关资源
最近更新 更多