本文介绍了承诺链中的.then(console.log())和.then(()= console.log())在执行方式上有何不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

效率上有区别吗?如果使用setTimeout代替console.log()

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

推荐答案

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

You can basically do these three things

.then(console.log())

这会立即调用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.

.then(console.log)

仅在promise成功解决(需要一个函数调用)并将隐含的promise传递给console.log函数之后,才执行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.

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

与以前相同,需要2个函数调用,但是您可以轻松地将一些其他参数传递给它.

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

在第二种情况下,要将附加参数传递给console.log,您需要使用 Function.prototype.bind 方法.

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

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));

在第一种情况下,console.log没有接收到参数.在第二种情况下,console.log隐式地从诺言中接收值,在第三种情况中,它却显式地接收了相同的值.

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.

在这种情况下,第二种情况与第三种情况之间唯一的性能差异是第三种情况又执行了一个函数调用(这是我们真正不必担心的事情).

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).

这篇关于承诺链中的.then(console.log())和.then(()= console.log())在执行方式上有何不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:49