DEV Community

Cover image for Code Smell 155 - Multiple Promises
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

4 1

Code Smell 155 - Multiple Promises

You have promises. You need to wait. Wait for them all

TL;DR: Don't block yourself in a sorted way.

Problems

  • Indeterminism

  • Performance bottleneck

Solutions

  1. Wait for all promises at once.

Context

We heard about semaphores while studying Operating Systems.

We should wait until all conditions are met no matter the ordering.

Sample Code

Wrong

async fetchOne() { /* long task */ }
async fetchTwo() { /* another long task */ }

async fetchAll() {
  let res1 = await this.fetchOne(); 
  let res2 = await this.fetchTwo();
  // they can run in parallel !!  
}

Enter fullscreen mode Exit fullscreen mode

Right

async fetchOne() { /* long task */ }
async fetchTwo() { /* another long task */ }

async fetchAll() {
  let [res3, res4] = await Promise.all([this.fetchOne(), this.fetchTwo()]);
  //We wait until ALL are done
}
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Semi-Automatic

This is a semantic smell.

We can tell our linters to find some patterns related to promises waiting.

Tags

  • Performance

Conclusion

We need to be as close as possible to [real-world]((https://dev.to/mcsee/what-is-wrong-with-software-5pa) business rules.

If the rule states we need to wait for ALL operations, we should not force a particular order.

Credits

Thanks for the idea

Photo by Alvin Mahmudov on Unsplash


JavaScript is the only language that I'm aware of that people feel they don't need to learn before they start using it.

Douglas Crockford


This article is part of the CodeSmell Series.

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (2)

Collapse
 
bwca profile image
Volodymyr Yepishev

Promise.allSettled() could prove to be a good alternative to Promise.all in some cases 🤓

Collapse
 
mcsee profile image
Maxi Contieri

indeed. i'll add it to the article

Scale globally with MongoDB Atlas. Try free.

Scale globally with MongoDB Atlas. Try free.

MongoDB Atlas is the global, multi-cloud database for modern apps trusted by developers and enterprises to build, scale, and run cutting-edge applications, with automated scaling, built-in security, and 125+ cloud regions.

Learn More

👋 Kindness is contagious

If this **helped, please leave a ❤️ or a friendly comment!

Okay