0

Why do we have to write function() {/*call some other function*/} or () => {} inside .then() in promise?

Let's say for example that we have one promise

someFn = () => {
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Resolved");
    }, 2000);
  })
}

And we also have random function

anotherFn = () => {
    console.log("in time");
}

To chain those functions we will use .then()

someFn().then(success => console.log(success)).then(() => anotherFn()); 

My question is, why is anotherFn() executed immediately if I write it like this .then(anotherFn()) and it waits with execution if it has () => {}?

As far as I know, the first argument that .then() takes is onFulfilled which is a function, and anotherFn() is also a function.

Mirakurun
  • 4,859
  • 5
  • 16
  • 32

1 Answers1

2

Wrapping your function in () => {...} is creating a new anonymous function that is waiting to be invoked.

By writing .then(anotherFunction()) you are invoking the function immediately upon being read. In your example as anotherFunction does not have a return value this would be equivalent to .then(undefined).

Step by step, what happens here is your code launches your async request, then continues to read ahead. In the then block it sees a function which is invoked immediately, the console.log runs returning undefined. Eventually the promise resolves and .then(undefined) is called.

Passing an invoked function to .then might be useful if anotherFunction was curried and returned from it a new function that should be executed on completion.

To make this work in the desired way you just need to just pass the function to the then block without invoking it (rather than passing it the return value of the function by invoking it).

.then(anotherFunction)

Here anotherFunction will be invoked with the return value from the promise only once it has resolved.

Josh
  • 1,517
  • 1
  • 13
  • 21