Search code examples
javascriptes6-promise

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


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


Solution

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