Jas*_*n C 4 javascript node.js promise bluebird
我正在阅读有关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;
});
};
Run Code Online (Sandbox Code Playgroud)
我对承诺仍然不满意,但从我到目前为止所学到的东西看起来很奇怪.我的问题是,上述功能是否与fetch()
直接返回并离开最终版本完全相同then()
:
var getEvents = function(participantId) {
return new models.Participant()
.query({where: {id: participantId}})
.fetch({withRelated: ['events'], require: true});
};
Run Code Online (Sandbox Code Playgroud)
也就是说,它仍然做同样的事情,返回相同的承诺,可以以相同的方式调用,等等?
根据我的理解,传递给函数的参数then
获取链中前一个promise的返回值.所以,在我看来.then(function (a) { return a; })
,一般来说只是一个无操作.对?
如果它们不一样,有什么区别?发生了什么,为什么作者这样写呢?
Ber*_*rgi 11
在我看来,这
.then(function (a) { return a; })
只是一个无操作.对?
它没用,应该省略.
发生了什么,为什么作者这样写呢?
这是一个大错.或者作者不理解承诺.
1:如果不一样,有什么区别?
与往常一样,有一些边缘情况.真的很奇怪.没有人应该使用(没有广泛的评论):
a)它返回一个新的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
Run Code Online (Sandbox Code Playgroud)
一般来说,不要做 then(function(a) { return a; })
归档时间: |
|
查看次数: |
1689 次 |
最近记录: |