Home > Blockchain >  Javascript Promise & event loop
Javascript Promise & event loop

Time:09-25

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

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!

CodePudding user response:

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
  • Related