Ling
Ling

Reputation: 41

What happens exactly when we call .then after a Promise is resolved?

I have a var to keep the promise object, and call .then in different places. I got the same timestamp for different .then. What happens when call .then to a already resolved promise object?

var promise1 = new Promise((resolve) => {resolve(Date.now().toString())})

promise1.then((response) => {console.log(response)});
promise1.then((response) => {console.log(response)});

Upvotes: 0

Views: 390

Answers (1)

jfriend00
jfriend00

Reputation: 707218

What happens exactly when we call .then after a Promise is resolved?

It schedules (right before the next tick of the event loop) for the .then() handlers to get called.

So, the current Javascript that is executing will continue to execute and finish and when it returns control back to the event loop, then the .then() handlers that were just registered on an already-resolved promise will call their callbacks in the order they were registered. Promise handlers are served before other things in the event loop so it doesn't actually go all the way into the event loop until there are no more promise callbacks to call.

So, it is always safe to register a .then() handler. You don't have to worry about whether the promise is already resolved or not. Either way, the .then() handler will get called (assuming the promise resolves or was already resolved).

So, if you modify the logging a bit like this:

const promise1 = new Promise((resolve) => {resolve(Date.now().toString())})

promise1.then((response) => {console.log("first .then()")});
promise1.then((response) => {console.log("second .then()")});
console.log("now here");

You will get this output:

now here
first .then()
second .then()

Upvotes: 1

Related Questions