Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 734
Zer0 Avatar asked Jun 13 '18 11:06

Zer0


People also ask

Does .then resolve a promise?

A then call will return a rejected promise if the function throws an error or returns a rejected Promise. In all other cases, a resolving Promise is returned.

How does console log the result of a promise?

then() method to access the value of a promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value of the promise as a parameter.

When chaining promises together what is returned with the reject method?

In the above program, a Promise object is created that takes two functions: resolve() and reject() . resolve() is used if the process is successful and reject() is used when an error occurs in the promise. The promise is resolved if the value of count is true.


1 Answers

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

like image 110
Matus Dubrava Avatar answered Oct 14 '22 04:10

Matus Dubrava