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

左心房为你撑大大i 提交于 2019-12-08 02:56:42

问题


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


回答1:


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.


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


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

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


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

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



来源:https://stackoverflow.com/questions/50836242/how-does-thenconsole-log-and-then-console-log-in-a-promise-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!