Skip to content

Latest commit

 

History

History
96 lines (56 loc) · 2.35 KB

File metadata and controls

96 lines (56 loc) · 2.35 KB

Code Smell 155 - Multiple Promises

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 fetchLongTask() { }
async fetchAnotherLongTask() { }

async fetchAll() {
  let result1 = await this.fetchLongTask(); 
  let result2 = await this.fetchAnotherLongTask();
  // But they can run in parallel !!  
}

Right

async fetchLongTask() { }
async fetchAnotherLongTask() { }

async fetchAll() {
  let [result1, result2] = 
      await Promise.all(
        [this.fetchLongTask(), this.fetchAnotherLongTask()]);
      // You 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]((https://github.com/mcsee/Software-Design-Articles/tree/main/Articles/Theory/What%20is%20(wrong%20with)%20software/readme.md) 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

Twitter

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

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code