DEV Community

Cover image for Can you answer this simple JS async interview question?
re4388
re4388

Posted on

Can you answer this simple JS async interview question?

See the blow question:

const promise = new Promise((resolve, reject) => {
    console.log(1);
    resolve(5);
    console.log(2);
}).then(val => {
    console.log(val);
});

promise.then(() => {
    console.log(3);
});

console.log(4);

setTimeout(function () {
    console.log(6);
});
Enter fullscreen mode Exit fullscreen mode

What will log out in order?

wait.


wait..


wait...


Okay.. here you are :)

--

Answer:

See this gist for answer


Explain:

We only need to remeber the prioirty is like this:
sync code -> micro tasks -> macro task

See this https://javascript.info/event-loop if you want to know why

First of all, What are the synchronous code runs in order?
1, 2, 4

Don't be fooled if you think the 1 and 2 inside the new Promise block is async code, these two console.log are sync code.

When we new up a new Promise, we immediately call those and only the resolve callback (and reject callback) are async.


Secondly, what are the mico tasks runs in order? 5, 3

Both of them are promise micro tasks and we know those belong to micro task


Finally, what's the macro task? 6

And that's the order!

const promise = new Promise((resolve, reject) => {
    console.log(1);   // <-- sync code 1
    resolve(5);
    console.log(2);   // <-- sync code 2
}).then(val => {
    console.log(val); // <-- micro code 1, log 5
});

promise.then(() => {
    console.log(3);   // <-- micro code 2
});

console.log(4);       // <-- sync code 3

setTimeout(function () {
    console.log(6);   // <-- macro code
});
Enter fullscreen mode Exit fullscreen mode

That's it for today :)

Top comments (1)

Collapse
 
monawwar profile image
Monawwar Abdullah

Thanks for sharing this.
Just to let you know, their are few spelling mistakes of "micro".