0

I've studied the event loop for a while and I get that everything synchronously will execute before anything asynchronously. But the following code leaves me baffled.

const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('A'), 0);
  console.log('B');
});
console.log('C');
promise.then((result) => console.log(result));

Everything that I've studied leads me to believe that this code returns C B A given the fact that C is the first console log that execute synchronously. A and B should go to the event loop. But if I run the code on a browser console, it returns B C A and I don't get why. I tried asking GPT but it returns different answers (CBA or BCA) depending who ask, so I can't trust it not even a little bit. Can someone explain this to me?

  • 1
    ChatGPT is not a JavaScript programmer. "B" is printed first because the callback to `new Promise()` is executed synchronously. The `setTimeout()` call returns immediately and then `console.log("B")` happens. All that is before `new Promise()` returns, and thus before `console.log("C")` happens. – Pointy Apr 03 '23 at 19:12
  • `so I can't trust it not even a little bit` - this is true! – James Apr 03 '23 at 20:13

0 Answers0