Rob*_*bin 8 javascript asynchronous promise meteor
我有多个Meteor.calls,其中每个方法都取决于另一个Meteor方法的响应.
客户
Meteor.call('methodOne', function(err, resOne){
if(!err){
Meteor.call('methodTwo', resOne, function(err, resTwo){
if(!err){
Meteor.call('methodThree', resTwo, function(err, resThree){
if(err){
console.log(err);
}
})
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
从Meteor的文档我知道
"调用客户端的方法是异步运行的,所以你需要传递一个回调来观察调用的结果."
我知道我可以在服务器上创建另一个Meteor方法来执行方法'methodOne','MethodTwo','MethodThree'使用Meteor.async包装,或者顺序没有回调.但是我担心这条路会导致我的流星方法变得臃肿和纠结,导致意大利面条代码.我宁愿保持每个Meteor方法只需要做一个工作,并找到一种更优雅的方式来链接客户端上的调用.任何想法,有没有办法在客户端使用Promises?
Ben*_*aum 13
由于另一个答案建议RSVP这个答案将建议Bluebird,它实际上是运行真正基准测试时最快的承诺库.而不是一个 没有真正衡量任何有意义的微观 基准.无论如何,我不是为了性能而选择它,我在这里选择它因为它也是最容易使用的和具有最佳可调试性的那个.
与其他答案不同,这个也不会抑制错误,并且由于没有调用promise构造函数,因此使函数返回promise的成本是微不足道的.
var call = Promise.promisify(Meteor.call, Meteor);
var calls = call("methodOne").
then(call.bind(Meteor, "methodTwo")).
then(call.bind(Meteor, "methodThree"));
calls.then(function(resThree){
console.log("Got Response!", resThree);
}).catch(function(err){
console.log("Got Error", err);
});
Run Code Online (Sandbox Code Playgroud)