aWebDeveloper aWebDeveloper - 6 months ago 26
Node.js Question

in bookshelf.js what does tap function do

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

Answer

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

edit: Due to a request for further clarification, 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 `it`,
    // 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);
  });
Comments