Regular promises have the beloved .then()
and .catch()
functions.
When promising
to retrieve an object that itself has properties that return promises we find chains of promises such as the following:
require("clientside-view-loader")
.then((view)=>
return view.load("clientside-view-modal-login_signup");
})
.then((compiler)=>{
return compiler.generate()
})
.then((modal)=>{
document.body.appendChild(modal);
modal.show("login");
})
This is UGLY!
How can we modify a promise to attach a custom property so that we can convert the above into the following?
require("clientside-view-loader")
.load("clientside-view-modal-login_signup")
.generate()
.then((modal)=>{
document.body.appendChild(modal);
modal.show("login");
})
note, these examples use the clientside-require
require
and not the nodejs
require
You don't modify promises at all. You just implement the builder pattern for the above promise chain.
No need to do anything complicated like subclassing
Promise
. If you want, you can also dynamically generate all these methods.Well, if you were looking for beautiful promise code, you would simply use modern
async
/await
syntax instead ofthen
callbacks:If you know the properties you wish to add in advance you can simply append a property to the promise like you would any other object:
Here's a function that does this for a dynamic set of properties:
Then
If you dont know the properties in advance (e.g., the properties are determined from a promise) you'll need to use a proxy that waits until that promise resolves to respond. This is answered here: How to add properties to a promise asynchronously?
Your initial code can be made shorter and more readable simply by using different syntax for your arrow functions. These two rules of arrow function syntax are relevant:
{}
and thereturn
removedThus, you could write your code like this, with the short form
view => …
instead of(view) => { return …; }
: