bookshelf.js中的tap函数是做什么用的?我在文档中没有找到任何相关条目。
return new Library({name: 'Old Books'})
.save(null, {transacting: t})
.tap(function(model) {
//code here
}
bookshelf.js中的tap函数是做什么用的?我在文档中没有找到任何相关条目。
return new Library({name: 'Old Books'})
.save(null, {transacting: t})
.tap(function(model) {
//code here
}
书架使用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);
});
tap()
时,您不必返回值,但是当使用then()
时(假设您希望该值通过 promise 链流动),则必须返回值。请参见我的更新答案以获取更完整的示例。 - dvlsg