我正在阅读 this tutorial about Bookshelf . Bookshelf 使用 Bluebird promises。有很多示例看起来像这样:
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true})
.then(function(model) {
return model;
});
};
我仍然对 promises 感到不舒服,但从我目前所了解的情况来看,这似乎很奇怪。我的问题是,上面的函数是否与直接返回 fetch()
并省略最后的 then()
完全一样:
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true});
};
也就是说,它仍然做同样的事情,返回同样的 promise ,可以用同样的方式调用,等等?
据我了解,传递给 then
的函数的参数获取链中先前 promise 的返回值。所以,在我看来 .then(function (a) { return a; })
通常只是一个空操作。对吧?
如果它们不一样,有什么区别?这是怎么回事,作者为什么要这样写?
最佳答案
It seems to me like
.then(function (a) { return a; })
is just a no-op. Right?
是。1
它没有用,应该省略。
What's going on and why did the author write it that way?
这是一个错误。或者作者不理解 promises。
1: If they aren't the same, what's the difference?
一如既往,有一些极端情况。真的很奇怪。没有人应该使用(没有广泛评论):
a) 它返回一个新的 promise 实例,一个不同的对象,以避免共享。但是,.then()
也可以。
b) 再次测试a
的可行性。既然应验了,忽然变成了应许,现在就要等候了。这当然会很糟糕。
关于javascript - ".then(function(a){ return a; })"是 promise 的空操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41089122/