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 ^ ^
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.
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!
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