Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Code Optimizations when Using Async/Await

--

Async/Await has been introduced to JavaScript in order to cope with the problem called the callback hell. Before async/await a couple of “intermediate” solutions tried to solve this problem:

  1. Using promises
  2. Using generators and the co library
  3. Using async/await as syntactic sugar for the second solution

When we apply solution 2 or 3, there is a risk that we do not make use of the biggest selling point of node.js. At least it was the biggest selling point for node.js back then when it gained traction. Which is the asynchronous nature and the non-blocking I/O.

# Inefficient
let result1 = await fetch('/request1');
let result2 = await fetch('/request2');
doSomeCalculation(result1);

As you see in the code above, the second request will only be executed after the first request has been answered, then the program waits for the second request to complete. Only after the second request is done the doSomeCalculation function is called. During the two requests the cpu was idle.

To be honest, in most cases it does not matter. Keep in mind: “premature optimization is the root cause of all evil” (see [01]). Anyway, to make thinks faster, we could write our code like this:

# Efficient
let request1 = fetch('/request1');
let request2 = fetch('/request2');
let result1 = await request1;
doSomeCalculation(result1);
let result2 = await request2;

This code has two performance benefits:

  1. We send both request at the same time without waiting for the first to finish.
  2. Assuming the first request is done much faster than the second request, we can already utilize the CPU and doSomeCalculation while waiting for the second request to finish. In this case, the shown code is better than Promise.all([request1, request2]).

Best Regards,

Oliver, working on MonsterWriter

[01] https://ubiquity.acm.org/article.cfm?id=1513451#:~:text=Trying%20to%20do%20the%20optimization,best%20practice%20among%20software%20engineers.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response