0

I read about event loop and callback queue and micro/macro task queue but maybe i am getting something the wrong way, Can someone visualize it for me?, it will help me understand so mush concepts.


console.log(1)
const wait2sec = new Promise((resolve, reject) => {
    console.log(2)
    setTimeout(() => {
        console.log(3)
        resolve(true)
    }, 2000)
    console.log(4)
})

const X =async () => {
    await wait2sec
    console.log('ok')
}
X()
console.log(5)

I think it should log: 1,5,2,4,3,ok but it logs: 1,2,4,5,3,ok

Keyvan Soleimani
  • 606
  • 2
  • 4
  • 16
Ahmed Hassan
  • 31
  • 1
  • 3

2 Answers2

0

From MDN (emphasis mine):

The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.

This is what happens here, the code of X and of wait2sec is run synchronously, hence before the console.log(5).

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32
0

You expected concurrent behavior between Promise object and console.log and don't saw it?

  1. You created and immediately called the Promise object (so you can't see 5 before 2,4, at least declare wait2sec as a function).
  2. Promise object without await or timeout runs as a synchronous function (so you see 2,4 and after 3)

if you want to see concurrency between two processes see such code:

function RandomWork(prefix) {
    return new Promise( resolve => {

        let time = Math.round(Math.random() * 10);
                 
        setTimeout(function() {
            console.log(prefix, 'made some work for:', time, 'ms') 
            resolve('foo');
          }, time);
      });
}

const Process = async(name) => {         

    const prefix = "process_"+name;

    console.log(prefix, 'start');

    for(let i=1; i<10; i++) {
        await RandomWork(prefix);
    }

    console.log(prefix, 'stop');
}

Process(1);
Process(2);
Mike
  • 36
  • 4