问题描述
给定一个命名函数用于处理 Promise
值
Given a named function utilized to handle a Promise
value
function handlePromise(data) {
// do stuff with `data`
return data
}
a)传递指定函数 handlePromise
作为对的引用.then()
a) Passing the named function handlePromise
as a reference to .then()
promise.then(handlePromise)
b)使用匿名或命名函数作为 .then()
的参数并返回指定函数 handlePromise
带 Promise
值作为传递给 .then()
b) Using an anonymous or named function as parameter to .then()
and returning the named function handlePromise
with Promise
value as parameter within the body of the anonymous or named function passed to .then()
promise.then(function /*[functionName]*/(data) {return handlePromise(data)})
问题
-
模式a)和b)之间是否存在差异?
Are there any differences between patterns a) and b)?
如果对1.的回答是肯定的,那么在使用任何一种模式时应该考虑
的差异是什么?
If the answer to 1. is yes, what are the differences that should beconsidered when using either pattern?
推荐答案
可以创建一个在没有传递参数时存在差异的情况,但是它是一个延伸,通常你应该传递 f
而不是 function(x){return f(x); }
或 x => f(x)
因为它更干净。
It is possible to create a case where there is a difference when no argument is passed, but it is a stretch and generally you should pass f
and not function(x) { return f(x); }
or x => f(x)
because it is cleaner.
这是一个导致差异的例子,理由是带参数的函数会导致副作用这些参数的效果:
Here is an example causing a difference, the rationale is that functions that takes parameters can cause side effects with those parameters:
function f() {
if(arguments.length === 0) console.log("win");
else console.log("Hello World");
}
const delay = ms => new Promise(r => setTimeout(r, ms)); // just a delay
delay(500).then(f); // logs "Hello World";
delay(500).then(() => f()) // logs "win"
这篇关于.then(functionReference)和.then(function(value){return functionReference(value)})之间是否存在差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!