是" .then(function(a){return a;})"承诺的无操作?

时间:2016-12-11 17:45:15

标签: javascript node.js promise bluebird

我正在阅读this tutorial about Bookshelf。 Bookshelf使用Bluebird承诺。有很多例子看起来像这样:

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的函数的参数获取链中前一个promise的返回值。所以,在我看来,.then(function (a) { return a; })一般只是一个无操作。正确?

如果它们不相同,那么区别是什么?发生了什么,为什么作者这样写呢?

2 个答案:

答案 0 :(得分:11)

  

在我看来,.then(function (a) { return a; })只是一个无操作。正确?

1

没用,应该省略。

  

发生了什么以及作者为何如此写作?

这是一个大错。或者作者没有理解承诺。

  

1:如果它们不相同,那么区别是什么?

与往常一样,有一些边缘情况。真的很奇怪。没有人应该使用(没有广泛的评论):
a)它返回一个新的promise实例,一个不同的对象,以避免共享。但是,.then()也是如此 b)a再次进行测试,以确定其可靠性。如果它自实现以来突然成为一种承诺,那么它现在将被等待。这当然很糟糕。

答案 1 :(得分:5)

Bergi的回答是正确的,但只是为了证明这不是一个无操作的案例,这是一个人为的例子,它不是一个无操作:

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

相关问题