我是 JS 的新手,正在学习 Promise。我想展示的代码摘录是这样的
promisedFunction.then(data=>console.log(data))
或者简单地
promisedFunction.then(console.log)
这相当于前面的代码摘录。问题是如何可能只使用then(console.log)
代替then(data=>console.log(data))
?这是否意味着我们可以在thenable回调中省略从promise传递的数据?
data=>console.log(data)
是一个函数,它接受一个参数并使用传入的参数调用一个方法。
如果你通过了console.log
它将执行相同的方法并仍然传递相同的参数。
实际上,您正在删除额外的函数调用 - 稍微更抽象一点,想象一下:
//some function `f`
const f = x => x + 1;
//different function `g` that just forwards the call to `f`:
const g = x => f(x);
console.log(g(41)); //42
的定义g
只是一个函数它所做的一切正在通话f
。其效果与f
功能。因此,我们可以将其重写为:
//some function `f`
const f = x => x + 1;
//different function `g` that just forwards the call to `f`:
const g = f;
console.log(g(41)); //42
and get exactly一样的效果。
在 Lambda 演算中,这种删除本质上为空的“包装函数”的操作被称为埃塔减少 https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B7-reduction.
因此,是的,两者.then(data => console.log(data))
and .then(console.log)
做完全相同的事情,您正在执行相同类型的转换,其中您正在取出虚拟转发功能。
然而,这并不是always一个选项。例如,如果删除转发功能最终将调用目标more参数,你可以得到不同的行为。一个臭名昭著的例子是parseInt当用于.map https://stackoverflow.com/questions/262427/why-does-parseint-yield-nan-with-arraymap:
const arrayOfString = ["1", "2", "3"];
const arrayOfIntegers1 = arrayOfString.map(parseInt);
const arrayOfIntegers2 = arrayOfString.map(x => parseInt(x));
console.log("arrayOfIntegers1", arrayOfIntegers1);
console.log("arrayOfIntegers2", arrayOfIntegers2);
问题是Array#map
调用回调three参数 - 项目、索引和数组。和parseInt
有一个可选的第二个参数 - 如果传入,它会更改数字的解析方式。所以你得到NaN
.
观察这一点的最简单方法是console.log
:
const arrayOfString = ["1", "2", "3"];
console.log(" --- using just `console.log` as callback ---");
arrayOfString.map(console.log);
console.log(" --- using just `x => console.log(x)` as callback ---");
const arrayOfIntegers2 = arrayOfString.map(x => console.log(x));
因此,只要中间函数具有相同的功能,就可以删除中间函数arity https://en.wikipedia.org/wiki/Arity作为它将被调用的内容以及下一个函数将被调用的内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)