在Bluebird / Bookshelf.js中,tap函数的作用是什么?

13
2个回答

24

书架使用Bluebird实现它们的承诺,我相信.tap()是他们特定的Promise方法之一。看起来它允许您在不改变通过链传递的值的情况下调用.then()

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

以下是Promise#tap()Promise#then()之间差异的示例。请注意,Promise#tap()不是标准的,是Bluebird特有的。

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);
  });

你能详细说明一下吗?我不明白then()会改变哪个值。我对bookshelf/ promises非常陌生。 - 1mike12
1
当使用 tap() 时,您不必返回值,但是当使用 then() 时(假设您希望该值通过 promise 链流动),则必须返回值。请参见我的更新答案以获取更完整的示例。 - dvlsg
1
现在我终于明白了!非常感谢您提供的额外说明。 - 1mike12

4
根据 Reg “Raganwald” Braithwaite 的说法,tap 是从各种 Unix shell 命令中借用的传统名称。它接受一个值并返回一个始终返回该值的函数,但如果您传递给它一个函数,则会执行该函数以产生副作用。 [source] 这里有同样的问题被提出,涉及 underscore.js。
要点是:tap 只是返回它所传递的对象。然而,如果传递了一个函数,它将执行该函数。因此,在不改变现有链的情况下,在现有链中执行副作用时,它非常有用于调试或执行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接