使用Fetch API时箭头函数加花括号出现undefined的原因
为什么箭头函数加花括号会让Fetch的响应变成undefined?
问题的核心在于箭头函数的两种语法规则:
- 当箭头函数使用无花括号的简洁体时,函数会自动返回箭头后表达式的结果,不需要写
return关键字。 - 当使用带花括号的块体时,函数不会自动返回任何值,必须显式写出
return,否则默认返回undefined。
对应到你的两段代码:
- 第一段代码里的第一个
then回调用了块体,但没有写return:
fetch(...url) .then((response) => {response.json()}) // 这里没写return,默认返回undefined .then((data) => {console.log(data)}) // 所以data是undefined
这个回调执行了response.json()但没有把它的返回值(一个Promise)传递给下一个then,导致后续拿到的data是undefined。
- 第二段代码用了简洁体,自动返回了
response.json()的Promise:
fetch(...url) .then((response) => response.json()) // 隐式返回Promise .then((data) => console.log(data)) // 正常接收JSON数据
如果想用块体写法,只需要加上显式的return就能解决问题:
fetch(...url) .then((response) => { return response.json() }) .then((data) => { console.log(data) }) // 现在可以正常打印预期的JSON输出
内容的提问来源于stack exchange,提问作者Valachio
相关产品推荐
相关产品推荐

