Pro tip: using Promise.then for function composition

Shalvah - Jun 26 '18 - - Dev Community

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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
getModels().then(manager.applyFilters)
Enter fullscreen mode Exit fullscreen mode

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .