通过提取请求从功能中返回数据

发布于 2025-01-28 18:03:46 字数 477 浏览 1 评论 0原文

我正在使用JS提取请求。 我在一个函数中具有此功能,当我调用函数时,我希望它返回我的数据。
这没有发生。
看来承诺没有得到“解决”。

我显然不完全理解承诺,因此与以下示例有关的任何建议都非常有用。

这是我的示例代码:

const test = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos')
  const data = await response.json()
  return data;
}

console.log(test())

输出:

// [object promise]
{}

问题:如何编写获取请求,以便在运行test()时,它会按照我的期望返回我的JSON?

谢谢

I am using js fetch request.
I have this inside a function, when I call the function I want it to return my data.
This is not happening.
It would appear that the promise is not getting 'resolved'.

I clearly don't fully understand promises, so any advice on that in relation to the below example would be very useful.

Here is my sample code:

const test = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos')
  const data = await response.json()
  return data;
}

console.log(test())

Output:

// [object promise]
{}

Question: How can I write the fetch request so that when I run test(), it returns me the json as I would expect?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文