I recently ran across a small code example that made me think about rigid conventions and how they can hamper understanding.
Here's the simplified example code:
return new Promise((resolve, reject) => {
locations.fetch({
success: resolve,
error: reject,
});
});
Not much to it, but it made me think. It's convention that the arguments of the callback to new Promise()
are resolve
and reject
. They don't have to be, though, and we can forget that there is a lot of flexibility available even in a simple example like this.
Variations
Changing Arguments
We know the arguments are functions that resolve and reject the promise. But the names can reflect their consumer, or anything at all.
return new Promise((success, error) => {
locations.fetch({ success, error });
});
This doesn't change the functionality of this code. It's still inside new Promise()
so it should be clear that it resolves and rejects. I'm not advocating for this change, though. It might take a moment longer to understand and the explicit names might be easier when skimming the code. This is about how expecting the convention of resolve
and reject
could lead us to misunderstand this perfectly valid code.
External Functions
We're probably so used to seeing an arrow function in new Promise()
that we might forget that it doesn't have to be that way.
const wrapFetch = (success, error) => {
locations.fetch({ success, error });
};
return new Promise(wrapFetch);
This same convention is probably more common in event handlers, where you might automatically expect to see (e) => // ...
repeated in the code.
Again, I'm not advocating for a coding style change, but I'm hoping we recognize how easy it is to get stuck in a convention and lose the ability to recognize code. We don't have to ignore convention, and we don't have to accept "clever" solutions to save a few characters, but a little practice testing the boundaries of convention can improve our ability to read and maintain code.
Top comments (0)