【问题标题】:Why does console.log not require an argument in this case?为什么在这种情况下 console.log 不需要参数?
【发布时间】:2017-07-15 17:50:48
【问题描述】:

如果我按如下方式使用 Fetch API:

fetch(url)
    .then(response => response.json())
    .then(console.log)

我知道这会记录前一个“then”的结果(响应数据),但是为什么在这种情况下 console.log 不需要任何参数?

这背后是否有任何技术推理或文档,是否可以使用任何其他内置方法?

【问题讨论】:

  • 因为then 接受一个回调,参数是从最后一个 then 返回的参数,所以参数被传递给 console.log。基本上是.then(function(json) { console.log(json) }).then(json => console.log(json))
  • 它与.then(thing => console.log(thing)) 相同,除了您不创建匿名函数并且所有参数都为您传递。任何可调用对象都可以这样使用。

标签: javascript es6-promise fetch-api


【解决方案1】:

这是简单的 Javascript,在这种情况下 console.log 需要该参数,这里发生的是 then 函数将回调作为其第一个参数,并使用最后一个 then 返回的参数在内部执行该回调功能。所以这意味着您正在传递console.log 函数的引用(或副本,我不确定),而不是直接执行。

总结起来就是:

function a (callback) {
  var something = 12345;
  callback(something);
}

a(console.log);

一样
a(function(something) {
  console.log(something);
})

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多