Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript await/async order of execution

So I'm trying to wrap my head about promises/await/async. I can't understand why when go() is executed the alert with "finished" go right after the console.log(coffee). Why does it only wait for getCoffee() and the other axios calls are ran after the "finished" alert when all functions are using await/promises?

function getCoffee() {
  return new Promise(resolve => {
    setTimeout(() => resolve("☕"), 2000); // it takes 2 seconds to make coffee
  });
}
async function go() {
  try {
    alert("ok");
    const coffee = await getCoffee();

    console.log(coffee); // ☕

    const wes = await axios("https://randomuser.me/api/?results=200");
    console.log("wes"); // using string instead of value for brevity

    const wordPromise = axios("https://randomuser.me/api/?results=200");
    console.log("wordPromise"); // using string instead of value for brevity

    alert("finish");
  } catch (e) {
    console.error(e); // 💩
  }
}
go();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
like image 658
CI_Guy Avatar asked Oct 16 '22 15:10

CI_Guy


2 Answers

The issue here is that console.log isn't always as synchronous as one might think. The specification only requires that console.log display a message in the developer console, but doesn't make any requirements about how or when the message will display. Depending on your browser, results may differ, however usually it's implemented something like the following:

  • When you make a call to console.log the request gets pushed onto a stack queue (so consecutive calls to console.log always execute in order)
  • On the next animation frame, the browser will attempt to process as much of the stack queue as possible (minimum of one element on the stack queue must be processed, so the browser may lock up if you attempt to log 8 megabytes of data)
  • "Processing" the stack queue involves things like converting DOM element references to links that take you elsewhere in the dev console, converting JSON objects to navigable and collapsible UI elements, or replacing objects with the text "[Object object]"
  • Once an element on the stack queue is processed, it must be rendered in the console. This requires adjusting the height of the console, determining if you need a scroll bar, determining where text will wrap, etc. This process (taking what you want in the console and actually displaying it on the screen) is called "painting"

Because console.log is actually a complex operation like this, it may not finish executing before the alert statement runs (in some browsers). By replacing every call to alert with console.log or every call to console.log with alert you should see that things are actually executing in the expected order.

like image 172
stevendesu Avatar answered Nov 15 '22 05:11

stevendesu


The async/await is working as intended. It is just that the the console takes some time to update or the browser is repainting, therefore the alert is triggered before it can repaint. You can verify it by using all alert instead of console.log. All the alert are executed in the correct order.As shown in the example below.

function getCoffee() {
    return new Promise(resolve => {
      setTimeout(() => {resolve("coffee")}, 2000); // it takes 2 seconds to make coffee
    });
  }
  async function go() {
    try {
      alert("ok");
      const coffee = await getCoffee();

      alert(coffee); // ☕

      const wes = await getCoffee();
      alert(wes);

      const wordPromise = getCoffee();
      alert(wordPromise);

      alert("finish");
    } catch (e) {
      console.error(e); // 💩
    }
  }
go();
like image 27
amrender singh Avatar answered Nov 15 '22 05:11

amrender singh