0

In one of Vue my components I have code that looks like this

<li class="comment" v-for="comment in comments">
  ...
</li>

And my computed method

computed: {
    comments() {
      // All filter UI elements are associated with a filter method
      // and when the user interacts with an element of the UI, filtersToApply gets populated with
      // the associated method. Not too important right now, 
      // it just checks whether user interacted with the UI or not, so it could essentially be a boolean. But I plan to make use of the functionality at a later time.
      const filtersToApply = this.filtersToApply();

      // if user hasn't interacted with the filter UI, just return the comments
      // else, apply filter(s) to comments
      if (filtersToApply.length === 0) {
        return this.$store.getters.comments;
      } else {
        return this.applyFilters(this.$store.getters.comments);
      }
    }

Ultimately, I want to do something like this:

// Apply the filters to the comments, one by one
applyFilters(comment) {
  return this.filterByX()
    .then(this.filterByY)
    .then(this.filterByZ)
    ....
}

where the filter methods look like

filterByX(comments) {
  return new Promise((resolve, reject) => {
    .......
    resolve(comments)
  })
}

How could I make this work? And is it a good pattern?

user1904218
  • 237
  • 1
  • 6
  • 2
    Why do you want to use Promises? – thanksd Jul 19 '17 at 15:33
  • 1
    Not something I've used much, but I feel like this would potentially be a good use case for currying. – Sam A. Horvath-Hunt Jul 19 '17 at 15:33
  • 1
    If filters aren't async, there's no point in using Promises. You can just compose functions with a helper `compose` function as described here: https://stackoverflow.com/a/44023242/7636961 This way you don't need to return a Promise from every filter. – Egor Stambakio Jul 19 '17 at 15:38
  • @thanksd good question, and I don't really have a good answer for it. I'm not very good at Javascript (or programming in general) but I thought promises made the code look a lot cleaner. – user1904218 Jul 19 '17 at 18:17

1 Answers1

0

Thanks to @wostex for pointing me in the right direction. Here's what I did (I'm using the lodash library to implement pipe):

Changed applyFilters function to

applyFilters(filters) {
  const filteredComments = _.flow(filters)
  return filteredComments(this.$store.getters.comments);
}

In the computed comments method I'm passing the array of filters to applyFilters which is the only other change I made.

  const filtersToApply = this.filtersToApply();

  if (filtersToApply.length === 0) {
    return this.$store.getters.comments;
  } else {
    return this.applyFilters(filtersToApply);
  }
user1904218
  • 237
  • 1
  • 6