0

I run the following code in Chrome, Firefox and NodeJS. The promise status showing in NodeJS and FireFox are pending. However, it is showing resolved in Chrome. Which one is the correct one?

var p1 = Promise.resolve(43).then(function(value) {
  return value;
});

console.dir(p1);

NodeJS:

Promise { <pending> }

FireFox:

Promise { "pending" }
<state>: "pending"

Chrome:

Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: 43
Sunny
  • 3
  • 1
  • The console uses lazy evaluation. In FF it shows "pending" because that's the *correct* status. In Chrome, you get the same thing but, the Promise object printed is collapsed, so when you expand it you get the *current* state which is "resolved". – VLAZ Oct 08 '19 at 12:51
  • 1
    Even if this weren't a side-effect of the [deferred evaluation in some consoles](http://stackoverflow.com/questions/38660832/element-children-has-elements-but-returns-empty-htmlcollection), it **wouldn't matter** which one was correct, it's **purely** an implementation detail. Other than with the console, you can never directly observe the status of a promise, by design. – T.J. Crowder Oct 08 '19 at 12:53

2 Answers2

0

The trick is in Chrome console window. The promise is in pending status when you print in console.log. Because the main thread is still executing. The code in promise is not even got to the thread, because the thread is still busy on console.log.

BUT, when you click on Promise in console, the value gets from the actual status on that moment when you click on it, which is resolved

You can verify that easily with console.logs from whiting promise and after the promise. As you see, promise value {} gets printed before the promise. The promise can NOT be in resolved while it's still executing, right?

var p1 = Promise.resolve(43).then(function(value) {
  console.log('inside promise');
  return value;
});

console.dir(p1);

Here's the trick, check the code below from devconsole, it would be {a:1}:

var a = {a: 0};
console.log(a)
a.a = 1
deathangel908
  • 8,601
  • 8
  • 47
  • 81
-1

To use promise results, you should:

Promise.resolve(43).then(function(value) {
  console.dir(value);
});

You are not supposed to use the promise object directly, but always via then and catch (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

sigmus
  • 2,987
  • 3
  • 23
  • 31