.then(functionReference) 和 .then(function(value){return functionReference(value)}) 之间有区别吗? [英] Are there differences between .then(functionReference) and .then(function(value){return functionReference(value)})?

查看:25
本文介绍了.then(functionReference) 和 .then(function(value){return functionReference(value)}) 之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个用于处理 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() 的参数,并以 Promise 值作为参数返回命名函数 handlePromise在传递给 .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)})

问题

  1. 模式 a) 和 b) 之间有什么区别吗?

  1. Are there any differences between patterns a) and b)?

如果 1. 的答案是肯定的,那么应该有哪些区别?使用任何一种模式时都考虑过吗?

If the answer to 1. is yes, what are the differences that should be considered when using either pattern?

推荐答案

可以创建一个case,在不传递参数的情况下有差异,但这是一个延伸,一般你应该传递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)}) 之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆