Configurable console logging inside a promise chain with _.curry
When using promise chains in Javascript, it is easy to think (at least for me) that you can only stick something non-configurable inside of it:
P.resolve(4).then(afunc).tap(console.dir).then...
But in fact with the help of the _.curry function from underscore/lodash you can curry functions, i.e. wrap them so that they can step-wise be configured with their parameters but only fire once all parameters are defined.
With help of the colors library one can define a console logging function with configurable color and message string and nice formatting, like so:
function log(logColor, message, data) { console.log(message) console.log(colors[logColor](JSON.stringify(data, null, 2))) }
And we can now configure that logging from inside of our promise chain like this:
P.resolve(4).then(afunc).tap(_.curry(log)('red','Inside the 4 chain')).then...
Above we call the log function with two of the three parameters. But since the last parameter data is missing, the curried function will first be executed when the parameter list is complete, which means the promise chain will trigger it.