javascript 承诺链中的 .then(console.log()) 和 .then(() => console.log()) 在执行上有何不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50836242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:17:47  来源:igfitidea点击:

How does .then(console.log()) and .then(() => console.log()) in a promise chain differ in execution

javascriptes6-promise

提问by Zer0

Is there any difference in efficiency? Will the behavior be any different if a setTimeout is used instead of console.log()

效率上有区别吗?如果使用 setTimeout 而不是 console.log() ,行为会有所不同吗

回答by Matus Dubrava

You can basically do these three things

你基本上可以做到这三件事

.then(console.log())

This calls the console.log immediately, without waiting until the promise is resolved, so it is not probably something that you would want to do.

这会立即调用 console.log,而无需等到 promise 得到解决,因此这可能不是您想要做的事情。



.then(console.log)

This executes the console.log only after the promise has successfully resolved (requires one function call) and implicitly pass the result of the promise to to the console.log function.

仅在承诺成功解析(需要一次函数调用)后才会执行 console.log 并将承诺的结果隐式传递给 console.log 函数。



.then(() => console.log())

Same as before, requires 2 function calls but you can easily pass some other arguments to it.

和以前一样,需要 2 个函数调用,但您可以轻松地向它传递一些其他参数。



To pass additional argument to the console.log in the second case, you need to use Function.prototype.bindmethod.

要在第二种情况下向 console.log 传递额外的参数,您需要使用Function.prototype.bind方法。

const promise = new Promise((resolve, reject) => {
  resolve('');
});
promise.then(console.log.bind(console, 'new arg'));

And to see all the three cases mentioned above in action

并查看上面提到的所有三个案例

const promise1 = new Promise((resolve, reject) => {
  resolve('promise 1');
});
promise1.then(console.log());

const promise2 = new Promise((resolve, reject) => {
  resolve('promise 2');
});
promise2.then(console.log);

const promise3 = new Promise((resolve, reject) => {
  resolve('promise 3');
});
promise3.then(v => console.log(v));

In the first case, console.log didn't receive and arguments. In the second case, the console.log received value from promise implicitly and in the third case it received the same value but explicitly.

在第一种情况下,console.log 没有接收和参数。在第二种情况下,console.log 隐式地从 promise 接收值,在第三种情况下,它接收到相同的值但显式。

In this scenario, the only difference in performance between the second and third case is that the third case performed one more function call (which is something that we don't really have to worry about).

在这种情况下,第二种和第三种情况在性能上的唯一区别是第三种情况又执行了一次函数调用(这是我们真正不必担心的事情)。