".then(function(a){ return a; })" 是 no-op for promises 吗?
Is ".then(function(a){ return a; })" a no-op for promises?
我正在阅读 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 感到不自在,但从我目前所了解的情况来看,这似乎很奇怪。我的问题是,上面的函数是否与直接 returning fetch()
并省略最后的 then()
:
完全一样
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true});
};
也就是说,它仍然做同样的事情,return同样的承诺,可以用同样的方式调用等等?
据我了解,传递给 then
的函数的参数获取链中先前承诺的 return 值。所以,在我看来 .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) 它 returns 一个新的 promise 实例,一个不同的对象,以避免共享。但是,.then()
也可以。
b) 再次测试 a
的可行性。既然应验了,忽然变成了应许,现在就要等候了。这当然会很糟糕。
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; })
我正在阅读 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 感到不自在,但从我目前所了解的情况来看,这似乎很奇怪。我的问题是,上面的函数是否与直接 returning fetch()
并省略最后的 then()
:
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true});
};
也就是说,它仍然做同样的事情,return同样的承诺,可以用同样的方式调用等等?
据我了解,传递给 then
的函数的参数获取链中先前承诺的 return 值。所以,在我看来 .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) 它 returns 一个新的 promise 实例,一个不同的对象,以避免共享。但是,.then()
也可以。
b) 再次测试 a
的可行性。既然应验了,忽然变成了应许,现在就要等候了。这当然会很糟糕。
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; })