Monday, 13 March 2017

Keeping Promise Chains Readable

I've grown used to promise chaining arrays. It's incredibly easy to read a promise chain when each promise is a line long such as

myArray.map(x => convertX)
  .filter()
  .whatever()
  .etc()

This is incredibly easy to read. However, when I create promise chains with custom functions, it gets much messier.

database.query(first query)
  .then(results => {
    // do stuff
    // do more
    // even more
    return database.query(second query)
  })
  .then(results => {
    // rinse and repeat
  })
  .catch(err => { 
    // error handling 
  })

Now, this can be legible, but when the promise chain extends further, it gets to be a little much. If I make each promise it's own function, then I can streamline the process so the code looks something like this (which imo, is 1000x more legible).

db.query(first query)
  .then(storeFirstQuery)
  .then(secondQueryAndStoreIt)
  .then(thirdQueryAndStoreIt)
  .catch(errHandlingFunction)

This way, I can rearrange the functions without having to manipulate the values that get passed from one promise to the next. If a promise uses a result of another, it only needs to be after the other, but not immediately after. That way I can sneak promises in wherever I need.

However, this requires my promise chain to use variables outside each promise's scope. Is there a tried and true way to do this?



via Matt

No comments:

Post a Comment