是“.then(function(a){ return a; })"吗?对承诺的无操作? [英] Is ".then(function(a){ return a; })" a no-op for promises?

查看:33
本文介绍了是“.then(function(a){ return a; })"吗?对承诺的无操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读本教程关于书架.Bookshelf 使用 Bluebird 承诺.有很多例子看起来像这样:

I'm reading this tutorial about Bookshelf. Bookshelf uses Bluebird promises. There's quite a few examples that look something like this:

var getEvents = function(participantId) {  
  return new models.Participant()
    .query({where: {id: participantId}})
    .fetch({withRelated: ['events'], require: true})
    .then(function(model) {
      return model;
    });
};

我仍然对 Promise 不满意,但从我目前了解到的情况来看,这似乎很奇怪.我的问题是,上述函数是否与直接返回 fetch() 并离开最终的 then() 完全相同:

I'm still not comfortable with promises, but from what I've learned so far this seems odd. My question is, is the above function exactly the same as returning fetch() directly and leaving off the final then():

var getEvents = function(participantId) {  
  return new models.Participant()
    .query({where: {id: participantId}})
    .fetch({withRelated: ['events'], require: true});
};

也就是说,它仍然做同样的事情,返回同样的promise,可以用同样的方式调用,等等?

That is, it still does the same thing, returns the same promise, can be called in the same way, etc?

据我了解,传递给 then 的函数参数获取链中前一个 promise 的返回值.所以,在我看来 .then(function (a) { return a; }) 通常只是一个空操作.对吗?

From what I understand, the parameter to the function passed to then gets the return value of the previous promise in the chain. So, it seems to me like .then(function (a) { return a; }) in general is just a no-op. Right?

如果它们不一样,那有什么区别?这是怎么回事,为什么作者要这样写?

If they aren't the same, what's the difference? What's going on and why did the author write it that way?

推荐答案

在我看来 .then(function (a) { return a; }) 只是一个空操作.对吗?

It seems to me like .then(function (a) { return a; }) is just a no-op. Right?

是的.1

没用,应该省略.

Yes.1

It is useless and should be omitted.

这是怎么回事,为什么作者要这样写?

What's going on and why did the author write it that way?

这是一个错误.或者作者不理解承诺.

It's a blunder. Or the author didn't understand promises.

1:如果不一样,有什么区别?

一如既往,有一些边缘情况.真是奇怪的人.没有人应该使用(没有大量评论):
a) 它返回一个新的 promise 实例,一个不同的对象,以避免共享.但是,.then() 也可以.
b) 再次测试 a 的 thenable-ness.要是兑现后突然变成了承诺,现在就等着吧.这当然会很糟糕.

As always, there are some edge cases. Really weird ones. That no-one should use (without extensive commenting):
a) it returns a new promise instance, a distinct object, to avoid sharing. However, .then() would as well.
b) a is tested again for its thenable-ness. If it suddenly became a promise since the fulfillment, it now will be awaited. This would be awful of course.

这篇关于是“.then(function(a){ return a; })"吗?对承诺的无操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆