Allen Ye
Allen Ye

Reputation: 15

Javascript Promise & event loop

I tried running the following code on Chrome and got an unexpected result.

<script>
    let p = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('OK');
        }, 1000)
    })
    console.log(p);
</script>

The Promise Object printed on Chrome console was enter image description here. (state='fulfilled', result='OK)

But the Promise Object printed on VScode console was enter image description here. (state='pending', result=undefined)

From what I learned about JS event loop, since setTimeout() is asynchronous, the code 'resolve('OK')' will not be executed untill the synchronous codes were done.

So I think the VScode result is what I should expect right? But what caused the different results between Chrome and VScode? Thank you ^ ^

Upvotes: 1

Views: 249

Answers (2)

AnanthDev
AnanthDev

Reputation: 1818

i'm guessing in vsc, the promise state is still in pending because the console.log() is fired before the timeout was completed, you could try this instead


const waitForTimeout = () => new Promise(resolve => setTimeout(() => resolve('OK'), 1000);

(async function() {
   const promise = await waitForTimeout();
   console.log(promise);
})(); // self fulfilling function

Upvotes: 1

ProfDFrancis
ProfDFrancis

Reputation: 9411

Beware that console.log on Chrome console shows you the most recent version of the variable

This is not necessarily the same as the value when the program was actually run.

So we have this weird situation. Try this in Chrome console.

let p = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('OK');
    }, 1000)
})
console.log("Value at time of running", JSON.stringify(p))
console.log("Value at time of seeing", p);

What I see is below. I am pasting it in, because I can't reproduce it through Stack Overflow's "snippet" feature.

enter image description here

What this means

The second console.log produces a confusing appearance. The summary of it (with the downward pointing arrow) says it is pending. But the detail of it, below, says it is fulfilled.

Clicking the blue "i" button gives some information. I can't easily copy and paste it here, but it says something along the lines of "the thing of the left is what it was at time of running console.log; the thing below is what it is now."

I have grown used to this over the years but I have to admit it is not obvious to me why we have both!

Upvotes: 2

Related Questions