On the front-end side of the stack, I write my fair share of AJAX calls. That is, getting and setting data from back-end services. Among the many different tools to accomplish this, I find using promises & partials to be very useful.
The functional pattern of getting XHR data with promises and partials allows one to write code that is more immutable and reusable.
Let's say we have a website, and want to display a certain user's profile from an AJAX call. We could create a simple jQuery function to do this:
That's simple enough right? All you'd need to do is call
getUserProfileAndDisplay(1234) and boom!
But what if you want to create many functions that perform similar tasks, and don't want
n number of functions that are only slightly different? Partials can help!
First, let's start with a basic function that creates partials:
Great! Now we can create a basic
If you notice that the
ajaxGetterExecutor function accepts four arguments, while the
ajaxGetter function only accepts two, you'll see that we're creating a partial function inside
url, data already applied. Now, the only arguments left to fulfill are the
reject arguments for the ES6 Promise. (More on Promises in a minute.)
We now have a function named
ajaxGetter that we pass a URL and some optional data. Lets put it to action…
However, we can take this even further by creating yet another partial, this time of
Now we have a function named
getUserProfile that only does one thing, but we also still have
ajaxGetter for any other needed operations.
Now that we have a dedicated function for getting user data, naturally we'll want to do something with that data. Let's get a user profile and display some basic parts:
Boom! That's easy enough right? But, what if we don't want a ton of functions that all do the same thing except for which jQuery node they're inserting into? We can just create a partial of the
display function, and pass it the node we want to update:
We know the correct order in which to do this because we're setting the array in the
There's so much that can be done using Promises & Partials (and even curried functions, but that's for another time). Please see below for some further reading on the topic: