Pro tip: using Promise.then for function composition

June 29, 2018 0 Comments

Pro tip: using Promise.then for function composition



I've become a fan of functional programming in recent times (even though I still don't know much about it). Over time, I've developed a habit when working with Promises in JavaScript. I try to construct my code so it ends up reading like this:

let tweetsToAttendTo = fetchTweets() .then(removeDuplicates) .then(removeTweetsIveRepliedTo) .then(fetchRelevantTweets); 

This means I'm using then not only to control flow but also to pipe output of one function to the input of another (thereby creating a pipeline). I find that this pattern makes the code easier to read and reason about, and gets rid of unnecessary filler like the arrow function and extra variable in the following:

fetchTweets() .then(tweets => removeDuplicates(tweets)); 

Be careful though! There are a few things you must know when using this pattern:

  1. Applying this method depends on the result of the previous function being the input to the next function

  2. Be careful when using object methods. For instance, the following two snippets of code aren't the same thing:

getModels().then(r => manager.applyFilters(r)) // any calls to this in manager.applyFilters will return undefined 

Ultimately, don't force it. I use this often, but if it just isn't working (output of F1 isn't input of F2, F2 behaves differently, I need to do special error handling), I let it go. Remember, no silver bullets!

Classic DEV Post from Mar 24



Tag cloud