DEV Community

Cover image for Promises, Async, and Speed: The JavaScript Cheatcode Your Senior Wonโ€™t Share! ๐Ÿš€
Tanishq510
Tanishq510

Posted on

Promises, Async, and Speed: The JavaScript Cheatcode Your Senior Wonโ€™t Share! ๐Ÿš€

"Why this list render is taking so long??"

Hey Devs,
If you are relying too much on await for your async calls, then it's time to think if you are trading your app performance.

Observe this code below:

const result1 = await asyncFunction1(); // 1 second
const result2 = await asyncFunction2();// 1 second
const result3 = await asyncFunction3();// 1 second

Enter fullscreen mode Exit fullscreen mode

The code looks okay for the first time, but the code execution is getting stopped for 1 second at each await.And going to take 3 seconds to process the code block

This particular code block is going to take 3 seconds to complete. But what if we can process all async calls in one go??

Promise.all()

The above code block can be performed simultaneously using Promise.all() method!!
And the execution time can be reduced down to 1 second (Since all the executions are being performed simultaneously)

const results = await Promise.all([asyncFunction1(), asyncFunction2(), asyncFunction3()]);
Enter fullscreen mode Exit fullscreen mode

Promise.all() in Action

// Create three async functions using setTimeout

function asyncFunction1() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("output----1");
      resolve(1); // Return 1
    }, 1000); // 1 second delay
  });
}

function asyncFunction2() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("output----2");
      resolve(2); // Return 2
    }, 2000); // 2 second delay
  });
}

function asyncFunction3() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("output----3");
      resolve(3); // Return 3
    }, 3000); // 3 second delay
  });
}

// Call the functions and measure execution time
async function executeAsyncFunctions() {
  console.time("Execution Time (Sequential)");
  const startTime = Date.now();

  const result1 = await asyncFunction1();
  const result2 = await asyncFunction2();
  const result3 = await asyncFunction3();

  const endTime = Date.now();
  console.timeEnd("Execution Time (Sequential)");

  console.log("Time Taken (Sequential):", endTime - startTime, "ms");
  console.log("Results:", result1, result2, result3);
}

async function executeAsyncFunctionsConcurrently() {
  console.time("Execution Time (Concurrent)");
  const startTime = Date.now();

  const results = await Promise.all([asyncFunction1(), asyncFunction2(), asyncFunction3()]);

  const endTime = Date.now();
  console.timeEnd("Execution Time (Concurrent)");

  console.log("Time Taken (Concurrent):", endTime - startTime, "ms");
  console.log("Results:", results);
}

executeAsyncFunctions();
executeAsyncFunctionsConcurrently();
Enter fullscreen mode Exit fullscreen mode

Observations!!

Sequential Execution (executeAsyncFunctions)
The above code block has executeAsyncFunctions all the async calls and it will take 7699 ms to process

Code execution with await

Concurrent Execution (executeAsyncFunctionsConcurrently)
On the other hand executeAsyncFunctionsConcurrently will execute the code concurrently and will finish in comparatively less time

Code execution with Promise

Conclusion

Promise.all() can be a saver for your JS application,specially when your code has multiple asynchronous calls.
await is good if you have one API call, but when dealing with multiple API calls Promise.all() is your goto guy for performance optimisation.

Homework

Promise Object comes with really helpful APIs,try to get yourself familiar with atleast the following!!

  1. Promise.all()
  2. Promise.allSettled()
  3. Promise.race()
  4. Promise.any()

"A Promise walked into a barโ€ฆ but never settled the bill." ๐Ÿบ

Top comments (0)