0

Having the usual fake api fetch request and call console.log() immediately.

const url = "https://jsonplaceholder.typicode.com/users";
const promise = fetch(url);
console.log(promise);

That returns the following:

Promise {<pending>} [[PromiseState]]: "fulfilled"

The question is: How do we already know (in synchronous console.log() operation) the state of the promise is fulfilled or rejected? And why the promise is pending and fulfilled at the same time?

Anthony
  • 73
  • 5
  • 1
    Use ``.then`` and ``.catch`` or ``async`` and ``await`` this will solve your problem. – Not A Bot Feb 01 '23 at 09:43
  • [`console.log` is not synchronous](https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects). – Quentin Feb 01 '23 at 09:46
  • 2
    Generally you shouldn't need to care if a promise is settled or not. In almost all cases, you just need to use `.then` or `await` / `.catch` or `try {} catch () {}` to do something when it *is* settled. – Quentin Feb 01 '23 at 09:47
  • 1
    The promise was pending when you called `console.log`, but fulfilled when you expanded the log entry in the console later, hence showing fulfilled at that point. – T.J. Crowder Feb 01 '23 at 09:47
  • 1
    *"And why the promise is pending and fulfilled at the same time?"* For the avoidance of doubt, you're absolutely right that a promise cannot be simultaneously *pending* and *fulfilled*, those are exclusive states. What you're seeing is the same as this: `const obj = {a: 1}; console.log(obj); obj.a = 2;` The entry summary shown by the `console.log` is `{a: 1}` because that was `a`'s value when the object was logged, but when you expand the entry, it shows `a: 2` because that's the value as of when you expanded it. – T.J. Crowder Feb 01 '23 at 09:55

0 Answers0