【发布时间】: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