在客户端上使用多个Meteor Method调用避免回调地狱

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)

  • 老实说,我可以说我学到了一些东西 - 我从来没有真正投入到承诺和/或链接承诺中,但如果只是非常简单的案例发挥作用,蓝鸟确实似乎是最好的选择,而不仅仅是表现明智.谢谢! (2认同)