MicroTask Queue vs CallBack Queue Interview Question

Table of contents

No heading

No headings in the article.

Welcome to my blog a blog where we will be going through an interesting interview question in JavaScript and understand everything around it.

I have a script where we have three Promisified functions and one Callback Function. Ideally Promisified functions should execute before Callback Function. But in my case, this is not happening and I wasn't able to tell the Interviewer the reason behind it.

const { log } = require("console");
const { fetch } = require ("fetch")


console.log("start program");

    setTimeout(()=>{
      console.log(" callback printed ");
  },100)


function myPolyfillPromiseAll(arr)
  {
    let results =[];
    let cnt =0;

    return  new Promise((resolve, reject)=>{
      arr.forEach(async (promise, idx)=>{

        try{
          results.push(await promise);
          cnt++;

          if(cnt === arr.length)
            resolve(results);
        }
        catch(err){
          reject(err);
        }

      }) 

    })  

  }

let p1= new Promise(function(res, rej){
  setTimeout(()=>{
    res("p1 promise");
  },100)
})

let p2= new Promise(function(res, rej){
  setTimeout(()=>{
    res("p2 promise");
  },100)
})

let p3= new Promise(function(res, rej){
  setTimeout(()=>{
    res("p3 promise");
  },100)
})

const ans = myPolyfillPromiseAll([p1, p2, p3]);

ans.then((data)=>{
  console.log(data);
}).catch((err)=>{
  console.log(err);
})

console.log("end  program");

Output

start program
end program
callback printed
[ 'p1 promise', 'p2 promise', 'p3 promise' ]

Reason Behind this

console.log(start program) and console.log(end program) executes first Then the callback function ( setTimeOut() ) enters into the Callback queue and Promisified Functions enters into the Microtask Queue.

Since in my code snippet, my Promisified Function is resolving a callback function i.e. setTimeOut(), so all the setTimeOut() functions enters into the callback queue for exectution.

p1.jpg

Till now our console has printed :

console.log(start program)
console.log(end program)

Now please look at the state of Microtask Queue and Callback Queue

Our callback Queue contains the starting one callback function i.e. setTimeOut(), and our Microtask Queue contains the Promise P1, P2 and P3.

Since our Promises P1, P2 and P3 are resolving an callback function, so they'll enter the Callback Queue for execution .

image.png

And event loop sees that Callstack is empty, so It'll send the first SetTimeOut ( not form Promise ) to the Callstack for execution and Promisified callback functions into the callback queue.

p3.jpg

The setTimeOut ( not from Promise ) will execute first followed by Primosified SetTimeOut Functions.

This is the reason for our output.

If we remove the callback functions from the Promise, then it prints the output as we expected .

const { log } = require("console");
const { fetch } = require ("fetch")


console.log("start program");

    setTimeout(()=>{
      console.log(" callback printed ");
  },100)


function myPolyfillPromiseAll(arr)
  {
    let results =[];
    let cnt =0;

    return  new Promise((resolve, reject)=>{
      arr.forEach(async (promise, idx)=>{

        try{
          results.push(await promise);
          cnt++;

          if(cnt === arr.length)
            resolve(results);
        }
        catch(err){
          reject(err);
        }

      }) 

    })  

  }

let p1= new Promise(function(res, rej){

    res("p1 promise");

})

let p2= new Promise(function(res, rej){

    res("p2 promise");

})

let p3= new Promise(function(res, rej){

    res("p3 promise");

})

const ans = myPolyfillPromiseAll([p1, p2, p3]);

ans.then((data)=>{
  console.log(data);
}).catch((err)=>{
  console.log(err);
})

console.log("end  program");

Output

start program
end program
[ 'p1 promise', 'p2 promise', 'p3 promise' ]
callback printed

I hope this helps, Thank you so much !