我正在阅读有关书架的本教程。书架使用蓝鸟承诺。有很多示例看起来像这样:
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true})
.then(function(model) {
return model;
});
};
我仍然对承诺不满意,但是据我所知,这似乎很奇怪。我的问题是,上述功能与直接返回fetch()
完全相同,并留下最终的then()
:
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true});
};
也就是说,它仍然做同样的事情,返回相同的诺言,可以以相同的方式来调用,等等?
?据我了解,传递给then
的函数的参数获得了链中先前承诺的返回值。因此,在我看来,.then(function (a) { return a; })
通常只是一个毫无疑问。对吗?
如果它们不一样,有什么区别?发生了什么,作者为什么要以这种方式写?
在我看来,
.then(function (a) { return a; })
只是一个no-op。对吗?
是。 1
它是没有用的,应省略。
发生了什么事,为什么作者以这种方式写入?
这是一个错误。或作者不明白承诺。
1:如果它们不一样,有什么区别?
a)它返回一个新的承诺实例,即一个不同的对象,以避免共享。但是, .then()
也会。
b)a
再次测试其当时的性能。如果自实现以来,它突然变成了诺言,现在将在等待。当然这将是可怕的。
bergi的答案是正确的,但仅仅是为了证明它不是一个没有的情况,这是一个人为的示例,其中它不是一个no-op:
o = {};
Promise.resolve(o).then(o => o.then = () => {}); // make thenable
Promise.resolve(o).then(console.log); // logs the object
Promise.resolve(o).then(x => x).then(console.log); // doesn't log the object
一般而言,不要做then(function(a) { return a; })