【问题标题】:async and await in inside app.js file in Node?在 Node 的 app.js 文件中异步和等待?
【发布时间】:2020-10-12 15:57:16
【问题描述】:
app.get("/", function (req, res) {
  async function showData() {
    const res = await fetch("api.openweathermap.org/data/2.5/weather?q=Berlin&appid={apiID}");
    const data = await res.json();
    console.log(data);
  }
})

//这里当我运行 node app.js 这应该记录终端内的数据,但我得到了错误。

【问题讨论】:

  • 为什么在 res.json() 之前使用 await?你能解释一下吗?
  • 这里 await before res.json() 类似于 .then。基本上,我在等待 API url 链接之后在 res.json() 之前使用 await 以获取 JSON 格式的响应。

标签: node.js asynchronous async-await


【解决方案1】:

Fetch 返回一个响应流。 查看answer to this question。使用 request-promise/request 模块或处理 fetch 返回的流。

【讨论】:

  • 在链接中我看到我们是 require("request") 模块来获取 API 调用。由于在平面 JS 中我们不需要任何模块,我们直接使用 fetch 函数并且使用 .then() 来获取日期。在提出的问题中,我尝试在不使用请求模块的情况下遵循相同的程序。谢谢!
  • 好的。尝试使用流来获取数据,然后在 res.on('end',callback) 中处理它,或者记录它。我可能会从不完整的代码中推断出这一点,但你是在某处调用 showData() 吗?
猜你喜欢
  • 2019-06-30
  • 2023-04-06
  • 2021-10-22
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多