Could somebody explain to me this JS code snippet?

I’m currently reviewing Promises in Javascript and how the event loop/Job queue ties with it.
I just need somebody to confirm whether my thinking is correct or not and if not explain it to me.

function foo(x) {
    return new Promise( function(resolve,reject){
    } );
var p = foo( 42 );
bar( p );
function bar(fooPromise) {

To my knowledge, the code above would be ran like this:
Function foo() is defined
We assign a promise to variable p
We run console.log(“B”) synchronously
bar(p) is ran but the resolve callbackfunction is then pushed into the Job Queue
We run console.log(“C”)
We then empty the Job Queue and run console.log(“D”)

Is my thinking correct?

1 Like

Hey @course7553316122 !

I find promises to be really tricky. Mainly because of the asynchronous queues that are going on.

So I ran your code snippet through the browser to see what would happen. It printed out the following:


I also asked ChatGPT to help out. It even hallucinated at one point too! Here’s a step-by-step explanation of why your code prints ABCD. I think what’s important to keep in mind is that the asynchronous queue runs after all synchronous code is executed.

  1. foo(42) is called. It runs console.log(A) and then the program moves onto the Promise.
  2. Because this promise is immediately resolved (by the way you don’t execute resolve. I’m assuming that was a typo), it prints “B”.
  3. The resolved promise is assigned to p, which again is resolved. This resolved promise is passed to bar()
  4. Bar assigns callback functions to the promise. Keep in mind these callback functions are called asynchronous and are called after the synchronous code finishes. So you can imagine these functions being added to another queue to wait.
  5. Console.log prints “C”
  6. At this point all the synchronous code is done. So now we’ll move onto the asynchronous code. In which case “D” is printed and “E” is printed.

Let me know what you think.