Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in bluebird / 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

like image 497
aWebDeveloper Avatar asked Apr 06 '16 06:04

aWebDeveloper


1 Answers

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: '[email protected]'
    };
    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);
  });
like image 126
dvlsg Avatar answered Sep 19 '22 20:09

dvlsg