Code Smell 155 - Multiple Promises

Photo by Alvin Mahmudov on Unsplash

Code Smell 155 - Multiple Promises

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

Maxi Contieri
·Aug 3, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Credits

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 !!  
}

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
}

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]((maximilianocontieri.com/what-is-wrong-with-..) 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.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com