Opinions on externally controlled promises?
Harry Dennen
Posted on April 17, 2018
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);
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?
💖 💪 🙅 🚩
Harry Dennen
Posted on April 17, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.