13

What does the bookshelf.js tap function do. I didn't find any entry in documentation

  return new Library({name: 'Old Books'})
    .save(null, {transacting: t})
    .tap(function(model) {
      //code here
    }

http://bookshelfjs.org/#Bookshelf-subsection-methods

aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242

2 Answers2

24

Bookshelf uses Bluebird for their promises, and I believe .tap() is one of their specific Promise methods. Looks like it allows you to essentially call a .then() without altering the value being passed through the chain.

http://bluebirdjs.com/docs/api/tap.html

Here is an example of the difference between Promise#tap() and Promise#then(). Note that Promise#tap() is not standard, and is Bluebird-specific.

var Promise = require('bluebird');

function getUser() {
  return new Promise(function(resolve, reject) {
    var user = {
      _id: 12345,
      username: 'test',
      email: 'test@test.com'
    };
    resolve(user);
  });
}

getUser()
  .then(function(user) {
    // do something with `user`
    console.log('user in then #1:', user);
    // make sure we return `user` from `#then()`,
    // so it becomes available to the next promise method
    return user;
  })
  .tap(function(user) {
    console.log('user in tap:', user);
    // note that we are NOT returning `user` here,
    // because we don't need to with `#tap()`
  })
  .then(function(user) {
    // and that `user` is still available here,
    // thanks to using `#tap()`
    console.log('user in then #2:', user);
  })
  .then(function(user) {
    // note that `user` here will be `undefined`,
    // because we didn't return it from the previous `#then()`
    console.log('user in then #3:', user);
  });
dvlsg
  • 5,378
  • 2
  • 29
  • 34
  • Could you elaborate? I don't understand what value would be altered by then(). I'm really new to bookshelf/ promises – 1mike12 Jun 01 '16 at 18:41
  • 1
    Sure. The gist of it is that you don't have to return a value when using `tap()`, but you do when using `then()` (assuming you want the value to flow through the promise chain). See my updated answer for a more full example. – dvlsg Jun 01 '16 at 19:00
  • 1
    Now I finally get it! Thank you so much for the additional writeup – 1mike12 Jun 02 '16 at 18:19
4

According to Reg “Raganwald” Braithwaite,

tap is a traditional name borrowed from various Unix shell commands. It takes a value and returns a function that always returns the value, but if you pass it a function, it executes the function for side-effects. [source]

Here is the same question being posed regarding underscore.js.

The gist is this: all tap does is return the object it was passed. However, if it is passed a function, it will execute that function. So, it is useful for debugging or for executing side-effects within an existing chain without altering that chain.

danyamachine
  • 1,848
  • 1
  • 18
  • 21