title: What does the callstack look like with promises and async/await?
body: <p>I recently watched this video: <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ" rel="nofollow noreferrer">https://www.youtube.com/watch?v=8aGhZQkoFbQ</a> and am trying to find a similar explanation for with Promises. Specifically in node.</p>
  
  <p>I'm probably wrong but I'm under the impression that Promises are placed on a microtask queue, the microtask queue is only processed when the callstack is empty and once the event-loop starts processing the microtask queue, it processes it until the queue is empty.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const sleep = (ms) =&gt; new Promise((res) =&gt; {
    setTimeout(res, ms)
  });
  
  const doTask1 = (workerId) =&gt; sleep(1000).then(() =&gt; console.log(`[${workerId}] Completed Task 1`));
  const doTask2 = (workerId) =&gt; sleep(5000).then(() =&gt; console.log(`[${workerId}] Completed Task 2`));
  
  const worker = async (workerId) =&gt; {
    console.log(`[${workerId}] Starting work`)
    await doTask1(workerId);
    await doTask2(workerId);
    console.log(`[${workerId}] Completed all tasks`);
  };
  
  worker('A');
  worker('B');</code></pre>
  </div>
  </div>
  </p>
  
  <p>When the snippet above is run, both worker A and B will start Task 1 and 2 at around the same time and complete at around the same time. I'm having trouble consolidating that behavior with what I've read/seen about Promises/microtasks and event-loops.</p>
  
  <p>I imagine that when the code executes, the call stack looks like:</p>
  
  <ol>
  <li>Callstack: [main.js]</li>
  <li>Callstack: [main.js][worker('A')]</li>
  <li>Callstack: [main.js][worker('A')][console.log()]</li>
  <li>Callstack: [main.js][worker('A')][await doTask1()]</li>
  </ol>
  
  <p>When we use <code>await</code>, what happens to the callstack? I suppose this is related to how generators work? </p>
  
  <ol start="6">
  <li>Callstack: ?? | Microtask Queue: [doTask1()]</li>
  </ol>
  
  <p><strike>What does it mean for the event-loop to "process" the microtask queue? Does processing <code>doTask1()</code> mean the event-loop is waiting 1 second? That doesn't sound right. Is the 1 second wait being done on a different thread (is that the right term?) as shown in the Youtube video's depiction of WebAPIs? Once the timeout is complete, the Promise's <code>res</code> goes onto the message queue where the event loop eventually picks it up and resolves the Promise? Does the callstack have to be empty for the callstack to execute <code>res</code>?</strike></p>
  
  <p>I'm stuck at this point and not sure what happens next in the callstack, the message queue, the microtask queue and how the event-loop decides what to do next.</p>