【问题标题】:A small confusion about the Fetch API [duplicate]关于 Fetch API 的一个小困惑 [重复]
【发布时间】:2019-12-11 19:28:37
【问题描述】:

我是异步 JavaScript 的新手,我一直在学习如何从 3rd 方 API 获取数据。在此过程中,我遇到了一个小问题:

const users = fetch('https://jsonplaceholder.typicode.com/users')
  .then((res) => { // <--- with curly braces
      res.json()
  })
  .then((data) => {
    console.log(data)
  })
const users = fetch('https://jsonplaceholder.typicode.com/users')
  .then((res) => res.json()) // <--- without curly braces
  .then((data) => {
    console.log(data)
  })

使用花括号,我得到的结果是undefined

而没有花括号,我得到了整个数据。

如何以及为什么会这样?有没有人遇到过这种情况?

【问题讨论】:

  • 该问题与fetch()无关。使用{ },您需要一个明确的return;没有{ } 你不会。
  • 我觉得自己很笨。我完全忘记了 ES6 语法。谢谢@Pointy

标签: javascript asynchronous fetch-api


【解决方案1】:

干草阿比舍克;

这是箭头函数的两种不同表示法:

  1. 带有表达式主体的箭头函数,在这种情况下,该表达式隐式/自动成为返回值
(a, b) => expression
  1. 以块语句为主体的箭头函数。这类似于“普通”函数表达式和声明,花括号表示块。您必须明确地return 一个值。
(a, b) => {
  statement;
  statement;
  return expression;
}

【讨论】:

  • 谢谢你,凯利。我现在才意识到这一点。
猜你喜欢
  • 1970-01-01
  • 2017-11-08
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2017-04-25
  • 2016-01-30
  • 1970-01-01
相关资源
最近更新 更多