我遇到了以下获取,但不明白它是如何工作的
fetch("https://api.github.com").then(res => res.json()).then(console.log)
转换为
json
后打印结果。
我通常会这样做
fetch("https://api.github.com").then(res => res.json()).then(res => console.log(res))
您能解释一下
console.log
如何访问结果吗?
console.log
是一个函数。 res => console.log(res)
也是如此。后者是一个简单的箭头函数,仅接受并使用一个参数,其中 console.log
,原始函数可以接受多个参数。
当提供单个参数时,两者是等效的,
res => console.log(res)
只是添加了不必要的包装层。如果你有一个顶级函数(不是方法,JS 不擅长绑定方法的概念),它已经满足了你的需要,就没有必要再给它包装一层额外的箭头函数包装。