DEV Community

Harry Dennen
Harry Dennen

Posted on

3 2

Opinions on externally controlled promises?

It's become a convenient pattern on my team to store resolve functions on an external object when coordinating some async work. Does anyone else use promises like this? Maybe there are some unforeseen pitfalls?

For instance, let's say we're loading images and doing some canvas draws with them.

class CatPichurs {
  constructor() {
    // promise control
    this.cats = {
      felix: {
        promise: new Promise(resolve => this.resolveFelix = resolve)
      },
      cheshire: {
        promise: new Promise(resolve => this.resolveCheshire = resolve)
      },
      garfield: {
        promise: new Promise(resolve => this.resolveGarfield = resolve)
      }
    }

    Promise.all([
      this.cats.felix.promise, 
      this.cats.cheshire.promise, 
      this.cats.garfield.promise
    ])
    .then(allTheCats => {
      allTheCats.forEach(cat => {
        // some big reveal logic
      })
    });
  }

}

class ExternalImageMagic {
  constructor(cats) {
    let felix, cheshire, garfield;

    // load some pictures and draw
    cats.resolveFelix(felix);

    // load more pictures and draw
    cats.resolveCheshire(cheshire);

    // and a couple of Garfield to draw
    cats.resolveGarfield(garfield);
  }
}

const someCats = new CatPichurs();
const imageStuff = new ExternalImageMagic(someCats);
Enter fullscreen mode Exit fullscreen mode

While this example makes no sense, you can see how this pattern is handy for keeping the cat rendering in one place and the image manipulation in another while ensuring both of them are coordinated.

What does the dev community think?

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more